Javascript whole in one
Table of contents
- Link .js to .html and error
- Commands
- Variables
- Get element by id
- Taking input from the user
- Type conversion
- Math functions
- Calculate Hypoteneus (practice program)
- Counter (practice program)
- Random number generator
- String methods and functions
- Slice
- Method chaining
- If, else if, else
- If else (Practice Program)
- Switch Statement
- Logical Operators (&&, ||, ! )
- Loops
- Break and continue
- Nested Loops
- Functions, nested functions, function expression, and arrow function
- Template Literals
- VAR vs LET
- Number guessing game
- Temperature converter
- Array
- Maps
- Objects
- This keyword
- Class
- Static variables and functions
- Inheritance
- Super Keyword
- Getters and Setters
- Instanceof operator
- Passing Object to function
- Array to Objects
- Anonymous Objects
- Simple Garage System
- Error handling
- setTimeout( )
- setInterval( )
- Date Object
- Simple Clock Program
- Synchronous and Asynchronous Code
- Console.time( )
Important Points:
- If indexof(); returns -1, it means this element does not exist in the array.
- console.log("Hello World");window.alert("This is a warning");
- console.log("Hello World") ... Print something on the console.
- window.alert("This is a warning"); ... Show alert message.
- var
let
const
are keywords for a variable. - document.getElementById("name").innerHTML = "Hello " + name; .
- document.getElementById("button").onclick
- name = document.getElementById("textbox").value
- console.log(typeof variable); ... to check type of variable.
- x = Number(x);y = String(y);z1 = Boolean(z1);
- Math functions:x = Math.round(x);x = Math.floor(x);x = Math.ceil(x);x = Math.pow(x, 5);x = Math.sqrt(x);x = Math.abs(x);x = Math.PI;
- String functions and methods:name.length; // no. of char in stringname.charAt(7); // char at index 7name.indexOf("d"); // index of 1st d in namename.lastIndexOf("d"); // index of last d in namename.trim(); // trim the empty spaces before and after namename.toUpperCase(); // convert all letters to uppercasename.toLowerCase(); // convert all letters to lowercasephone.replaceAll("-", ""); // replace "-" elements within string with ""
- Slice:firstname = fullname.slice(0, 8); // ending index is exclusivelastname = fullname.slice(14); // starting index is inclusive // is no ending index, it means till endfirstname = fullname.slice(0, fullname.indexOf(" "));lastname = fullname.slice(fullname.indexOf(" ") + 1);
- Box checked:document.getElementById("b3").checked; // return 1 if box is checked, 0 if not
- var and let are keywords for the variables.
- Using let is preferred.
- let age = 21; // intconsole.log(age);
- let name = "Developer-256"; // stringconsole.log("Happy Birthday ", name);
- let status = false; // boolconsole.log("Enrolled: ", status);
You write everything between ``, and when you have to write some variable, you use ${}
Example:
23: toLocaleString():
It takes a string and returns a string with language-sensitive representations of that number.
- locale: specify the language (undefined = default)
- options: objects with formatting options ie currency etc.
24: var vs let:
- Variable scope: Where the variable is accessible.
- Let variables are limited to block scope ie {}.
- Var variables are limited to function () {}.
- Any variable outside every function and every scope is a Global variable.
- If a var is used as a global variable, then it can change the browser's window properties ie var name = "Developer"; // this will change the browser's window property name = "" to name = "Developer".let name = "Developer" // browser's window name property will remain name = "".
25: Number Guessing game:
- Element: The current value that is being iterated in a for-each loop.
- Index: Index of current element.
- Array: Array of current element.
| Method | Description |
|---|---|
| new Map() | Creates a new Map object |
| set() | Sets the value for a key in a Map |
| get() | Gets the value for a key in a Map |
| clear() | Removes all the elements from a Map |
| delete() | Removes a Map element specified by a key |
| has() | Returns true if a key exists in a Map |
| forEach() | Invokes a callback for each key/value pair in a Map |
| entries() | Returns an iterator object with the [key, value] pairs in a Map |
| keys() | Returns an iterator object with the keys in a Map |
| values() | Returns an iterator object of the values in a Map |
| Property | Description |
|---|---|
| size | Returns the number of Map elements |
28: Objects:
Objects are a group of properties (variables) and methods (functions).
29: This:
this refers to the current object.
30: Class:
Class is a blueprint for creating objects.
OR
31: Static variables and functions:
Static variables and functions belong to class not objects.
So you cannot access them with an object ie car1.startRace() is wrong. You have to use Car.startRace();
Static variables: are useful for cashes and fixed-configuration.
Static functions: are useful for utility functions.
32: Inheritance:
We use extends keyword while inheriting one class to another.
class child extends parent {} is the syntax and JS does not support multiple inheritance (inherit from more than one class).
33: Super keyword:
Super keyword is used to invoke the constructor of parent when you are making a constructor for the child class.
Super constructor must be invoked above everything in the child constructor.
34: Getters and Setters:
Getters and Setters are used to get and set data respectively but in addition, they bind the object variable to a special function the they are set or get.
They are used if you want to set data with certain limitations etc.
35: Instanceof operator:
It returns true if the object belongs to a class or class inheriting from it.
36: Passing object to function:
37: Array of objects:
38: Anonymus Objects:
- These are the objects without a specific name.
- These cannot be directly referenced and are referenced using array name and index.
- They require less syntax.
- No need for unique names.
39: Simple Garage System:
40: Error handling:
Errors are the objects with the description of something that went wrong. They occur when:
- Can't open a file
- Lose connection
- The user types incorrect input
- TypeErrors
In error handling, you wrap the dangerous code (ie user inputs etc) with try block and if an error occurs the code performs something else so that the error does not occur and your program keeps running.
- Try: Use try block to wrap the dangerous code.
- Catch: Use catch to handel the error.
- Throw: Use throw to throw a user-defined error. Mostly used at places when something will go wrong and wont cause an error.
- Finally: Use finally to represent the block of code that will execute regradless of these is an error or not.
41: setTimeout( ):
This function invokes a function after a set number of milliseconds.
It is an asynchronous function ie it doesn't pause the execution.
- The first argument within the brackets can be a callback (name of function without brackets), or function expression (function without a name ie function(){} ), or an arrow function expression ( () => {} ).
- The second argument is the number of milliseconds after which the block is executed.
42: setInterval( ):
This invokes the function repeatedly after a set number of milliseconds.
This is also an asynchronous function (doesn't pause execution)
43: Date Object:
Date is an object that has many getters and setters function for elements like date and time
44: Simple Clock:
HTML:
45: Synchronous and Asynchronous Code:
Synchronous Code:
- It is the code that executes in a sequence.
- It executes as step-by-step linear instructions which means start now, finish now ie before execution of the next statement, first must end.
- Out of sequence.
- Start now, and finish sometime later.
- Ex. Access a database, fetch a file, task that takes some time.
46: Console.time( ):
- It is a method of console object.
- You can calculate the time to track how long a synchronous function took to execute.
- It only works for synchronous functions.
48: CallBack:
- A callback is a function that is passed as an argument to another function.
- While passing a callback, you can only pass the function name.
- If you add ( ) or (arguments), it will throw an error.
- You have to take its arguments along with callback and then pass it to callback within the function like:let order = (fruit, topping, callback) => {console.log(`Order Placed`);
callback(fruit, topping); }
let production = (fruit, topping) => {console.log(`${fruit} ice-cream with ${topping} toppings is ready`);}order("Strawberry", "chocolate", production);// production is a callback passed to order function and Strawberry and chocolate are args that will be passed to callback - Sometimes callbacks are used so that the second function does not execute before the first one.
// Via function:
// Via arrow function:
// Via async function:
// Via async arrow:
- It is an interface for changing the content of web pages using JS.
- It works like an API.
- It is like everything within your HTML is enclosed in a document object and you can access everything within your HTML using DOM.
- .firstElementChild: gives the first child of the list.document.querySelector("#veges").firstElementChild.style.backgroundColor = "yellow";
- .lastE1ementChild: gives the last child of the list.document.querySelector("#veges").lastElementChild.style.backgroundColor = "yellow";
- .nextElementSibling: gives next sibling list if a list is selected or next element sibling if a single element of the list is selected.document.querySelector("#veges").nextElementSibling.style.backgroundColor = "yellow";
- .previousElementSibling: gives previous sibling list if a list is selected or previous element sibling if a single element of the list is selected.document.querySelector("#veges").previousElementSibling.style.backgroundColor = "yellow";
- .children[ ]: you can access the children of a list using .children[ ] and passing the index of children. But these are not iterateable.document.querySelector("#veges").children[0].style.backgroundColor = "yellow";
- Array.from(.children): you can make array of all children of a list.const veg = document.querySelector("#veges");const childrenArray = Array.from(veg.children);childrenArray.forEach((child) => { child.style.backgroundColor = "yellow"; });
- innerHTML:
This is not preferred as it is vulnerable to XSS attacks.<h1 id="tag"></h1><script>document.getElementById("tag").innerHTML = "This is a heading";</script> - .textContent:
This is the preferred way as it changes XSS to text.<h1 id="tag"></h1><script>document.getElementById("tag").textContent = "This is a heading";</script>
- Adding new element at the end of the list:<ul id="fruits"><li>apple</li><li>mango</li><li id="a">orange</li></ul><script>const newElement = document.createElement("li");newElement.textContent = "banana";document.getElementById("fruits").append(newElement);</script>
- Adding element at the beginning of the list:<ul id="fruits"><li>apple</li><li>mango</li><li id="a">orange</li></ul><script>const newElement = document.createElement("li");newElement.textContent = "banana";document.getElementById("fruits").prepend(newElement);</script>
- Adding element in the middle of the list:
Use insert before method and first pass element to add and the pass index in the list where to add. You can select all list by using querySelectorAll or tagName etc.<ul id="fruits"><li>apple</li><li>mango</li><li id="a">orange</li></ul><script>const newElement = document.createElement("li");newElement.textContent = "banana";document.getElementById("fruits").insertBefore(newElement, document.getElementsByTagName("li")[2]);</script>
57: Changing the style property of HTML using JS:
- .onclick: perform something when the element is clicked.This will also work:const box = document.getElementById("box");box.onclick = makeRed;<div id="box" onclick="makeRed()" style="background-color: aqua;width: 8rem;height: 8rem;"></div>
- .onload: perform something when the element is loaded with web page.const box = document.getElementById("box");box.onload = window.prompt("Hello");
- .onmouseover: performs something when the mouse cursor is over the element.let box = document.getElementById("box");box.onmouseover = makeRed;
- .onmouseout: performs something when the mouse cursor leaves the element.let box = document.getElementById("box");box.onmouseover = makeRed;box.onmouseout = makeBlue;
- .onmousedown: performs something while the element is clicked.let box = document.getElementById("box");box.onmousedown = makeRed;
- .onmouseup:let box = document.getElementById("box");box.onmousedown = makeRed;box.onmouseup = makeBlue;
This method is the recommended way of handling events in JS because:
- You can add many event handlers to one element.
- Even the same event that invokes different functions
- First, you can pass which event should you handle.
- Secondly, which function is called when that event occurs.
- Thirdly, if two elements are taking same space and are listening for same event, you can select which one should be handled first by pass true to the event which should be handled first.
60: Show / Hide element in HTML using JS ( Display vs Visibility ):
- The display property shows or removes the element from the DOM.
- While the visibility property changes the opacity of the element (0% or 100%) while keeping the element within the DOM.
61: Detect key press:
- keydown
- kepress
- keyup

Comments
Post a Comment