Javascript whole in one

 Table of contents

  1. Link .js to .html and error
  2. Commands
  3. Variables
  4. Get element by id
  5. Taking input from the user
  6. Type conversion
  7. Math functions
  8. Calculate Hypoteneus (practice program)
  9. Counter (practice program)
  10. Random number generator
  11. String methods and functions
  12. Slice
  13. Method chaining
  14. If, else if, else
  15. If else (Practice Program)
  16. Switch Statement
  17. Logical Operators (&&, ||, ! )
  18. Loops
  19. Break and continue
  20. Nested Loops
  21. Functions, nested functions, function expression, and arrow function
  22. Template Literals
  23. VAR vs LET
  24. Number guessing game
  25. Temperature converter
  26. Array
  27. Maps
  28. Objects
  29. This keyword
  30. Class
  31. Static variables and functions
  32. Inheritance
  33. Super Keyword
  34. Getters and Setters
  35. Instanceof operator
  36. Passing Object to function
  37. Array to Objects
  38. Anonymous Objects
  39. Simple Garage System
  40. Error handling
  41. setTimeout( )
  42. setInterval( )
  43. Date Object
  44. Simple Clock Program
  45. Synchronous and Asynchronous Code
  46. Console.time( )




Important Points:

  1. If indexof(); returns -1, it means this element does not exist in the array.







1: Link .js to .html:
            To link .js and .html use the following command at the end of the program just above the closing body tag. This is because you have to write everything in HTML before this tag, or it will give an error.

<script src="index.js"></script>
document.getElementById("name").innerHTML = "Hello " + name;





2: Commands: 
  1. console.log("Hello World");window.alert("This is a warning");
  2. console.log("Hello World") ... Print something on the console.
  3. window.alert("This is a warning"); ... Show alert message.
  4. var let const 
    are keywords for a variable. 
  5.  document.getElementById("name").innerHTML = "Hello " + name; .
  6. document.getElementById("button").onclick
  7. name = document.getElementById("textbox").value
  8. console.log(typeof variable); ... to check type of variable.
  9. x = Number(x);
    y = String(y);
    z1 = Boolean(z1);
  10. 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;
  11. String functions and methods:
    name.length;  // no. of char in string
    name.charAt(7);  // char at index 7
    name.indexOf("d");  // index of 1st d in name
    name.lastIndexOf("d");  // index of last d in name
    name.trim(); // trim the empty spaces before and after name
    name.toUpperCase();  // convert all letters to uppercase
    name.toLowerCase();  // convert all letters to lowercase
    phone.replaceAll("-", "");  // replace "-" elements within string with ""
  12. Slice:
    firstname = fullname.slice(0, 8); // ending index is exclusive
    lastname = fullname.slice(14);  // starting index is inclusive // is no ending index, it means till end
    firstname = fullname.slice(0, fullname.indexOf(" "));
    lastname = fullname.slice(fullname.indexOf(" ") + 1);
  13. Box checked:
    document.getElementById("b3").checked; // return 1 if box is checked, 0 if not





3: Variables: 
  1. var and let are keywords for the variables.
  2. Using let is preferred.
  3. let age = 21; // int
    console.log(age);
  4. let name = "Developer-256"; // string
    console.log("Happy Birthday ", name);
  5. let status = false; // bool
    console.log("Enrolled: ", status);
All datatypes:

/* null */      let a = null;
/* number */    let b = 345;
/* boolean */   let c = true;
/* bigint */    let d = BigInt("4315234232");
/* string */    let e = "Developer";
/* symbol */    let f = Symbol("This is a symbol");
/* undefined */ let g = undefined;

console.log(a); // null
console.log(b); // 345
console.log(c); // true
console.log(d); // 4315234232n
console.log(e); // Developer
console.log(f); // Symbol(This is a symbol)
console.log(g); // undefined

console.log("\n");

console.log(typeof a); // object
console.log(typeof b); // number
console.log(typeof c); // boolean
console.log(typeof d); // bigint
console.log(typeof e); // string
console.log(typeof f); // symbol
console.log(typeof g); // undefined




4. Getting something in HTML via id and replacing it or rewriting it: 
        
HTML:
<p id="name"></p>

Js:
let name = "developer-256";
document.getElementById("name").innerHTML = "Hello " + name;






5. Taking input from the user:

Non-practical way:
let name = window.prompt("Enter your name: ");
console.log(name);


Practical way:

HTML:
<div class="input">
        <label>Enter your name below:</label>
        <br>
        <input type="text" id="textbox">
        <br>
        <button id="button">submit</button>
        <h2 id="Name"></h2>
    </div>

CSS:
label {
    font-size: 2rem;
    font-weight: bold;
}

.input input {
    width: 30%;
    margin: 1rem 0rem;
    font-size: 1.5rem;
    border: 2px solid black;
}

.input button {
    margin: 0.5rem 0rem;
    font-size: 1.5rem;
}

.input h2 {
    font-size: 2rem;
}

Js:
let name;

document.getElementById("button").onclick = function () {
    name = document.getElementById("textbox").value;

    console.log(name);
    document.getElementById("Name").innerHTML = "Hello " + name;
}




6: Type conversion:

Conversion of 1 datatype to other.
It is mostly used because the input from used is always in string datatype. So in order to perform arithmetic operations, you have to typecast string to number.

let x = "255";
let y = 255;
let z1 = "Hello";
let z2= "";


console.log(typeof x);  // string
x = Number(x);
console.log(typeof x);  // number


console.log(typeof y);  // number
y = String(y);
console.log(typeof y);  // string


console.log(z1);  // Hello
z1 = Boolean(z1);
console.log(z1);  // true


console.log(z2);  // [empty string]
z2 = Boolean(z2);
console.log(z2);  // false

So, Boolean if empty gives false, otherwise, it gives true. This can be used to check if the user entered something or not.





7: 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;





8: Calculate hypotenuse (practice program):

Impractical way:
let x = window.prompt("Enter length of side A: ");
x = Number(x);

let y = window.prompt("Enter length of side B: ");
y = Number(y);

let z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
console.log("Hypotenuse: ", z);

Practical way:

HTML:
<div class="div">
    <label>Base:<input type="text" id="aBox"></label>
    <br>
    <label>Altitude:<input type="text" id="bBox"></label>
    <br>
    <button id="button">Submit</button>
    <br>
    <br>
    <h2 id="result"></h2>
</div>    

Js:
document.getElementById("button").onclick = function() {
    let x = document.getElementById("aBox").value;
    x = Number(x);
   
    let y = document.getElementById("bBox").value;
    y = Number(y);

    let z = Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2));
    document.getElementById("result").innerHTML = "Hypoteneus: " + z;
}






9: Counter Program:


HTML:
<div class="counter">
    <p id="num"></p>
    <button id="b1">Increase</button>
    <button id="b2">Reset</button>
    <button id="b3">Decrease</button>
</div>

Js:
let num = 0;
document.getElementById("num").innerHTML = num;

document.getElementById("b1").onclick = function() {
    num += 1;
    document.getElementById("num").innerHTML = num;
}

document.getElementById("b2").onclick = function() {
    num = 0;
    document.getElementById("num").innerHTML = num;
}

document.getElementById("b3").onclick = function() {
    num -= 1;
    document.getElementById("num").innerHTML = num;
}





10: Random number generator:

let x = Math.ceil(Math.random() * 6); // Math.floor(Math.random() * 6) + 1;
let y = Math.ceil(Math.random() * 6); // Math.floor(Math.random() * 6) + 1;
let z = Math.ceil(Math.random() * 6); // Math.floor(Math.random() * 6) + 1;

console.log(x);
console.log(y);
console.log(z);




11: String methods and functions:

let name = "Muhammad Umar Chaudhry";
let phone = "123-456-789";

console.log(name);
console.log(name.length);  // no. of char in string
console.log(name.charAt(7));  // char at index 7
console.log(name.indexOf("d"));  // index of 1st d in name
console.log(name.lastIndexOf("d"));  // index of last d in name
console.log(name.trim()); // trim the empty spaces before and after name
console.log(name.toUpperCase());  // convert all letters to uppercase
console.log(name.toLowerCase());  // convert all letters to lowercase
console.log(phone.replaceAll("-", ""))  // replace "-" elements within string with ""

// substring() for selecting particular a part of a string.
console.log(name.substring(9, 13)); // first is inclusive and second in exclusive
console.log(name.substring(9)); // this will print everything after, including this index
console.log(name.substring(-5, 8)); // index is never -ve so it will be considered 0
console.log(name.substring(9.75)); // index cannot be in decimal so it will be rounded down to the lesser whole number






12: Slice:

let fullname = "Muhammad Umar Chaudhry";
let firstname;
let lastname;

firstname = fullname.slice(0, 8); // ending index is exclusive
lastname = fullname.slice(14);  // starting index is inclusive // is no ending index, it means till end

console.log(fullname);
console.log(firstname);
console.log(lastname);



firstname = fullname.slice(0, fullname.indexOf(" "));
lastname = fullname.slice(fullname.indexOf(" ") + 1);

console.log(fullname);
console.log(firstname);
console.log(lastname);




13: Method chaining:
            Calling one method after another in one continuous line code.

let username = "Muhammad umar Chaudhry";

console.log(username.charAt(username.indexOf(" ") + 1).toUpperCase().trim());




14: If, else if, else:

let age = -2;

if (age > 65) {
    console.log("You are a senior citizen");
}

else if (age > 30) {
    console.log("You are an adult");
}

else if (age > 0) {
    console.log("You are a child");
}

else {
    console.log("You are not born yet");
}




15: If else (Practice Program):

HTML:
    <div class="check">
        <button id="submit">Submit</button><br>
       
        <label for="sub">Subscribe</label>
        <input type="checkbox" name="" id="sub"><br>
        <br><br>
       
        <label for="b1">Pyoneer</label>
        <input type="radio" name="payment" id="b1"><be>
       
        <label for="b2">Jazz Cash</label>
        <input type="radio" name="payment" id="b2"><be>
       
        <label for="b3">Easy Paisa</label>
        <input type="radio" name="payment" id="b3">

    </div>

Js:
document.getElementById("submit").onclick = function () {
    const checkBox_checked = document.getElementById("sub").checked;
    const Payoneer = document.getElementById("b1").checked;
    const Jazz_cash = document.getElementById("b2").checked;
    const Easy_Paisa = document.getElementById("b3").checked;
    if (checkBox_checked) {
        if (Payoneer) {
            console.log("You paid using Payoneer");
        }
        else if (Jazz_cash) {
            console.log("You paid using Jazz Cash");
        }
        else if (Easy_Paisa) {
            console.log("You paid using Easy Paisa");
        }
        else {
            console.log("You didn't paid");
        }
    }
    else {
        console.log("You didn't subscribed");
    }
}





16: Switch Statement:

let day = 6;

switch (day) {
    case 1:
        console.log("Monday");
        break;

    case 2:
        console.log("Tuesday");
        break;

    case 3:
        console.log("Wednesday");
        break;

    case 4:
        console.log("Thursday");
        break;

    case 5:
        console.log("Friday");
        break;

    case 6:
        console.log("Saturday");
        break;

    case 7:
        console.log("Sunday");
        break;

    default:
        console.log("Invalid Input");
        break;
}

And

let grade = 95;

switch (true) {
    case grade > 90:
        console.log("Grade: A");
        break;
       
    case grade > 80:
        console.log("Grade: B");
        break;

    case grade > 70:
        console.log("Grade: C");
        break;

    case grade > 50:
        console.log("Grade: D");
        break;

    case grade < 50:
        console.log("Grade: F");
        break;

    default:
        console.log("Invalid Input");
        break;
}





17: Logical operators ( &&{and}, || {or}, ! {not} ):

let temp = 15;
let sunny = true;

if (temp > 0 && temp < 30 && sunny) {
    console.log("Weather is fine outside\n");
}
else {
    console.log("Weather is not fine outside");
}



let sunny = true;

if (!sunny) {
    console.log("It's cloudy outside");
}

else {
    console.log("It's sunny outside");
}



18: Loops:
 
While loop: (repeat code an infinite amount of times)
let username = "";

while (username == "" || username == null) {
    username = window.prompt("Enter your name: ");
}

console.log("Hello " + username);

Do-While loop:
let username;

do {
    username = window.prompt("Enter your name: ");
} while (username == "" || username == null);

console.log("Hello " + username);

For loop (repeat code a certain amount of times):

let num = 10;

for (let i = 0; i < num; i++) {
    console.log(i); 
}






19: Break and Continue:

for (let i = 0; i < 20; i++) {
    if (i == 6) {
        break;
    }
    console.log(i);  
}
// 1 2 3 4 5


for (let i = 0; i < 10; i++) {
    if (i == 5) {
        continue;
    }
    console.log(i);
}
// 1 2 3 4 6 7 8 9




20: Nested loops:

HTML:
    <div class="content">
        <h1 id="element"></h1>
    </div>

Js:
let character = window.prompt("Enter the character to make rectangle of: ");
let rows = window.prompt("Enter the number of rows: ");
let columns = window.prompt("Enter the number of columns: ");


for (let i = 0; i < rows; i++) {
    for (let j = 0; j < columns; j++) {
        document.getElementById("element").innerHTML += character;
   
    }
    document.getElementById("element").innerHTML += "<br>";
}





21: Functions, nested functions, function expression, and arrow function:

Function:

function function_name(parameters) {
    //code
}

Function expression:
            In JS, a function can also be written in the form of an expression and can be stored in a variable. In this way, you can make an anonymous function that does not have any specific name and can be called by the name of the variable. 
    It is a good practice to use const with the variable in which the function is stored.

const sum = function (a, b) { return a + b; }; // ; at end is of whole expression

let result = sum(5, 10);
console.log(result);

Arrow function:
        The arrow function is a compact way of writing function expressions.
// If there is only one statement of code and it is a return statement, then don't write return or {}
const sum = (x, y) => x + y;

console.log(sum(6, 8));

// If there is more than one line of code, you can write a return statement.
const result = (a, b) => {
    if (a > b) {
        return a;
    } else {
        return b;
    }
};

console.log(result(2, 6));

Nested functions:

These are functions within a function. Nested functions are hidden outside the parent function ie you cannot access them by calling them ie functionName();

let userName = "Developer";
let userInbox = 5;

login();

// following functions will not run because they are inaccessible due to their nested nature
// displayUserName();
// displayUserInbox();

function login() {
    displayUserName();
    displayUserInbox();

    function displayUserName() {
        console.log(`Welcome ${userName}`);
    }
    function displayUserInbox() {
        console.log(`You have ${userInbox} new messages`);
    }
}






22: Template Literals:
        In template literals, instead of double quotes or single quotes, you use backticks (``) ie the first key of the UK layout keyboard.

 You write everything between ``, and when you have to write some variable, you use ${}

Example: 

let name = "Developer";
let semester = 2;
let university = "Harvard";

console.log(
`Hello ${name}
You study at ${university}
You are in semester # ${semester}`
)






23: toLocaleString():

            It takes a string and returns a string with language-sensitive representations of that number.

number.toLocaleString(locale, {options});

  1. locale: specify the language (undefined = default)
  2. options: objects with formatting options ie currency etc.
let myNum = 123456.78
// let result = myNum.toLocaleString("en-US", {style: "currency", currency: "USD"});
let result = myNum.toLocaleString("hi-IN", {style: "currency", currency: "INR"});

console.log(result);








24: var vs let:

  1. Variable scope: Where the variable is accessible.
  2. Let variables are limited to block scope ie {}.
  3. Var variables are limited to function () {}.
  4. Any variable outside every function and every scope is a Global variable.
  5. 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:

<body>
    <div class="bg-red-500 text-center">Number Guessing Game</div>
    <div>Make a choice from 1 - 10 :</div>
    <br>
    <label>Enter your Choice : </label>
    <input type="text" class="border border-black" id="choice"><br>
    <button id="button" class="border border-black px-4 py-1 mt-5 bg-green-300 hover:bg-blue-300">Submit</button>
    <br>
    <br>
    <br>
    <h1 id="result" class="text-3xl"></h1>

    <script>
        const $number = Math.floor(Math.random() * 10 + 1);
        let $button = document.querySelector("#button");
        let $tries = 0;

        $button.addEventListener("click", () => {
            let $guess = document.getElementById("choice").value;
            $guess = Number($guess);
            $tries++;

            if ($guess < $number) {
                alert("Try Higher");
            } else if ($guess > $number) {
                alert("Try Lower");
            } else {
                document.getElementById("result").innerHTML = `Congrats! You guessed it<br>It took you ${$tries} tries`;
            }
        })
    </script>
</body>







24: Temperature Converter:

<body>
    <div class="bg-red-500 text-center">Temperature Converter</div>
    <br>
    <label>Enter Temperature : </label>
    <input type="text" class="border border-black" id="choice"><br><br>
    <input type="radio" name="temp" id="ctemp"><label>To Celcius</label><br>
    <input type="radio" name="temp" id="ftemp"><label>To Fahrenheit</label><br>
    <button id="button" class="border border-black px-4 py-1 mt-5 bg-green-300 hover:bg-blue-300">Submit</button>
    <br>
    <br>
    <h1 id="result" class="text-3xl"></h1>

    <script>
        let $button = document.getElementById("button");
        $button.addEventListener("click", () => {
            let $temp;
            if (document.getElementById("ctemp").checked) {
                $temp = Number(document.getElementById("choice").value);
                $temp = toCelcius($temp);
                document.getElementById("result").innerHTML = `${$temp}°C`;
            } else if (document.getElementById("ftemp").checked) {
                $temp = Number(document.getElementById("choice").value);
                $temp = toFahrenheit($temp);
                document.getElementById("result").innerHTML = `${$temp}°F`;
            } else {
                alert("Select Temperature to convert into !");
            }
        })

        function toCelcius(x) {
            return (x - 32) * 5 / 9;
        }
        function toFahrenheit(x) {
            return (x * 9 / 5) + 32;
        }
    </script>
</body>





26: Array:

let fruits = ["apple", "mango", "orange"];

fruits[3] = "banana"; // add element to index 3
fruits.push("strawbery"); // add element to end of array
fruits.pop(); // removes element from the end of array
fruits.unshift("grapes"); // add element to the start of array
fruits.shift(); // removes element from the start of array

let length = fruits.length; // gives length of array {not fruits.length()}
let index = fruits.indexOf("orange"); // gives index of specific element. If it is -1, it means this element doesnot exists.



Iterating over an array:

let fruits = ["apple", "mango", "orange"];

// printing all fruits by for loop
for (let i = 0; i < fruits.length; i++) {
    console.log(fruits[i]);
}

// printing all fruits by for loop but in reverse order
for (let i = fruits.length - 1; i >= 0; i--) {
    console.log(fruits[i]);
}

// for of loop
for (const fruit of fruits) {
    console.log(fruit);
}


Sorting an alphabetic array:

let fruits = ["orange", "apple", "mango"];

// sorting array in alphabetic order
fruits.sort();
for (const fruit of fruits) {
    console.log(fruit);
}

// sorting array in reverse alphabetic order
fruits.sort().reverse();
for (const fruit of fruits) {
    console.log(fruit);
}


2D array:

let fruits = ["apple", "mango", "orange"];
let vegetables = ["carrot", "onion", "potato"];
let meats = ["chicken", "mutton", "fish"];

// Making a 2D array
let grocerylist = [fruits, vegetables, meats];

// change specific element of 2D array (say we want to change mutton with beef)
grocerylist[2][1] = "beef"; // [rows][columns]

// printing entire grocerylist
for (const list of grocerylist) {
    for (const item of list) {
        console.log(item);
    }
}

// Iterating over 2D array
let rows = 3, columns = 3;
for (let i = 0; i < rows; i++) {
    for (let j = 0; j < columns; j++) {
        console.log(grocerylist[i][j]);
    }
}


Spread Operator ( ... ) : 
            The Spread operator unpacks the elements in the iterable ie an array or a string. Thus it allows you to quickly copy one array to the other or quickly print all the members of the array.

// Finding maximum in an array using spread operator
let numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
let max = Math.max(...numbers);
console.log(max);

// Copying two arrays in a single array
let fruits = ["apple", "mango", "pineapple", "grapes"];
let vegetables = ["potato", "onion", "carrot", "ginger"];
let groceryList = [...fruits, ...vegetables];

// Printing all elements in the array using spread operator
console.log(...groceryList);


Rest Parameter : 
            They represent an indefinite number of parameters. They are used to pack arguments into an array.

// Add undefined number of values using rest parameters
console.log(sum(1, 2, 3, 4, 5));

function sum(...numbers) {
    let result = 0;
    for (const number of numbers) {
        result += number;
    }
    return result;
}
// You can now also do console.log(sum(1, 2, 3, 4, 5, 6, 7, 8, 9, 10));


// Example # 2
console.log(result(6, 7, 8, 9, 10));

function result(x, y, ...values) {
    let total = x * y;
    for (const value of values) {
        total += value;
    }
    return total;
}


Callback : 
            A function passed as an argument to another function.
It ensures that a function is not going to run before a task is completed. Helps us develop asynchronous code. (When one function has to wait for another function) that helps us avoid errors and potential problems.
Example: Wait for a file to load.

// when calculation is performed, print it on html page using callback

calculation(5, 6, printOnScreen); // don't write callBack()

function calculation(x, y, callBack) {
    let result = x * y;
    printOnScreen(result);
}

function printOnScreen(x) {
    document.getElementById("text").innerHTML = x;
}


Array.forEach( ):
        Execute the given callback function for every element of the array. 
In the callback function, you can take 3 parameters:
  1. Element: The current value that is being iterated in a for-each loop.
  2. Index: Index of current element.
  3. Array: Array of current element.
Example: Capitalizing every first character in every word in an array.

let students = ["abdullah", "umar", "usman", "haider"];
// in students array, performing capitalization() on every element.
students.forEach(capitalization); // no () because its a callback
students.forEach(print);

function capitalization(element, index, array) { // or x, y, z
    // in every element of array at specific index for which the function is callback,        make first character to uppercase, then join every character after index 0 to it        and store it in same array at same index
    array[index] = element[0].toUpperCase() + element.substring(1);
}
function print(element) { // we don't need to always write all three
    console.log(element);
}


Array.map( ) :
        Execute the given callback function for every element of the array and then store the result in new array. 

let numberArray = [1, 2, 3, 4, 5, 6, 7, 8, 9];
// performing callback function and storing result in new arry
let squaresArray = numberArray.map(square);
let cubesArray = numberArray.map(cube);

// printing new arrays
squaresArray.forEach(print);
console.log('\n');
cubesArray.forEach(print);

// defining functions
function print(element) {
    console.log(element);
}
function square(element) {
    return Math.pow(element, 2);
}
function cube(element) {
    return Math.pow(element, 3);
}


Array.filter( ) :
        Creates a new array with all elements that pass the test provided as callback. 

let ages = [5, 15, 32, 21, 14, 67, 17, 91];
// performing test and storing in new array
let adults = ages.filter(bigAge);
let children = ages.filter(smallAge);

// printing new arrays
adults.forEach(print);
console.log('\n');
children.forEach(print);

// defining functions
function print(x) {
    console.log(x);
}
function bigAge(x) {
    return x >= 18;
}
function smallAge(x) {
    return x < 18;
}


Array.reduce( ) :
        Reduce array to a single value generally by performing mathematical operation.
Example: When you want to sum all the prices of elements in the cart. 

let prices = [5, 10, 15, 20, 25, 30];
// calculating the total using reduce() and storing in total
let total = prices.reduce(sum); // this callback will be called again and again untill last element

function sum(x, y /* or total, elements */) {
// first is the variable in which you have to store result in each iteration and second the the element    of array on which we are currently working.
    return x + y;
}

console.log(total);


Sorting a numeric array:

let grades = [90, 100, 50, 70, 60, 80];

grades = grades.sort(ascendingSort); // calling callback
grades.forEach(print);
grades = grades.sort(descendingSort);
grades.forEach(print);

function print(element) {
    console.log(element);
}
function ascendingSort(x, y) { // for ascending, first x, then y
    return x - y;
}
function descendingSort(x, y) { // for descending, first y, then x
    return y - x;
}


Shuffle an array:

let unshuffledCards = ['A', '2', '3', '4', '5', '6', '7', '8', '9', '10', 'J', 'Q', 'K'];
console.log(...unshuffledCards); // A 2 3 4 5 6 7 8 9 10 J Q K
let shuffledCards = shuffle(unshuffledCards);
console.log(...shuffledCards); // 2 8 4 J K 7 9 6 Q 10 A 3 5

function shuffle(array) {
    for (let i = array.length - 1; i >= 0; i--) {
        let random = Math.floor(Math.random() * array.length);
        let temp = array[i];
        array[i] = array[random];
        array[random] = temp;
    }
    return array;
}






27: Maps:

A JS Map is a collection of key/value pairs that can use any type of data as a key or value and remember the order of its entries.
MethodDescription
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
PropertyDescription
sizeReturns the number of Map elements
// 1. new Map([]): Create new map
// Create new map by passing array of arrays of keys and values => Map( [array] )
let storeMap = new Map([
    ["Shirts", 20],
    ["Pants", 30],
    ["Jackets", 150],
    ["Socks", 5],
])
// storeMap.forEach((value, key) => console.log(`${key} : $${value}`)); // print all values

// 2. Map.set(): Add elements to map
storeMap.set("Shoes", 45);

// 3. Map.get(): Get value of a key
let temp = storeMap.get("Jackets")

// 4. Map.size: Get number of elements in a map
temp = storeMap.size;

// 5. Map.delete(): remove an element
storeMap.delete("Shoes");

// 6. Map.clear(): removes everything form Map
storeMap.clear();

// 7. Map.has(): Returns true if element exists in map
temp = storeMap.has("Shirts");


For more: click here




28: Objects:

        Objects are a group of properties (variables) and methods (functions).

const car = {
    // properties or variables
    model: "Mustang",
    color: "Blue",
    year: 2017,

    // methods or functions
    drive: function () { console.log(`You are driving`); },
    brake: function () { console.log(`You applied the brake`); }
}

console.log(`Car's model is: ${car.model}`);
console.log(`Car's color is: ${car.color}`);
console.log(`Car's model year is: ${car.year}`);
car.drive();
car.brake();





29: This:

        this refers to the current object.

const car = {
    model: "Mustang",
    color: "Blue",

    display: function () {
        // wrong because we cannot access the variables in functions of class or object use this keyword
        // console.log(`Model: ${model} \n Color: ${color}`);
        console.log(`Model: ${this.model} \nColor: ${this.color}`);
    }
}
car.display();







30: Class:

        Class is a blueprint for creating objects.

class Complex {
    // Variables:
    real;
    imaginary;

    // Constructor:
    constructor(x, y) {
        this.real = x;
        this.imaginary = y;
    }

    // functions:
    display() {
        console.log(`Real part: ${this.real} \nImaginary: ${this.imaginary}`);
    }
}

// creating object
const c1 = new Complex(5, 10);
c1.display();

OR

class Complex {
    // You can ignore creating variables if you make constructor like this

    // Constructor:
    constructor(real, imaginary) {
        this.real = real;
        this.imaginary = imaginary;
    }

    // functions:
    display() {
        console.log(`Real part: ${this.real} \nImaginary: ${this.imaginary}`);
    }
}

// creating object
const c1 = new Complex(5, 10);
c1.display();





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.

class Car {
    // static totalCars; wrong because no initialization of static
    static totalCars = 0;

    constructor(model) {
        this.model = model;
        // this.totalCars += 1;// wrong because static belong to class
        Car.totalCars += 1;
    }

    static startRace() {
        console.log(`3...2...1...GO!`);
    }
}

let car1 = new Car("Honda");
let car2 = new Car("Kia");
let car3 = new Car("Hyundai");

// car1.startRace(); wrong because static function
Car.startRace();

// console.log(car1.totalCars); wrong because static variable
console.log(`Total cars: ${Car.totalCars}`);





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).

class Animal {
    constructor(alive, name) {
        this.alive = alive;
        this.name = name;
    }

    eat() {
        if (this.alive) {
            console.log(`${this.name} is eating.`);
        } else {
            console.log(`${this.name} can't eat.`);
        }
    }
    sleep() {
        if (this.alive) {
            console.log(`${this.name} is sleeping.`);
        } else {
            console.log(`${this.name} is dead.`);
        }
    }
}

class Hawk extends Animal {
    constructor(alive, name) { super(alive, name); } //automatically called even if not written
    fly() {
        if (this.alive) {
            console.log(`${this.name} is flying.`);
        } else {
            console.log(`${this.name} can't fly.`);
        }
    }
}

class Fish extends Animal {
    constructor(alive, name) { super(alive, name); } //automatically called even if not written
    swim() {
        if (this.alive) {
            console.log(`${this.name} is swimming.`);
        } else {
            console.log(`${this.name} can't swim.`);
        }
    }
}

class Rabbit extends Animal {
    constructor(alive, name) { super(alive, name); } //automatically called even if not written
    run() {
        if (this.alive) {
            console.log(`${this.name} is running.`);
        } else {
            console.log(`${this.name} can't run.`);
        }
    }
}

let h1 = new Hawk(true, "Shaheen");
let f1 = new Fish(false, "Machlee");
let r1 = new Rabbit(true, "Buggs Bunny");

h1.eat();
h1.sleep();
h1.fly();
console.log('\n');

f1.eat();
f1.sleep();
f1.swim();
console.log('\n');

r1.eat();
r1.sleep();
r1.run();






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.

class Animal {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

class Hawk extends Animal {
    constructor(name, age, flySpeed) {
        super(name, age);
        this.flySpeed = flySpeed;
    }
}

class Fish extends Animal {
    constructor(name, age, swimSpeed) {
        super(name, age);
        this.swimSpeed = swimSpeed;
    }
}

class Rabbit extends Animal {
    constructor(name, age, runSpeed) {
        super(name, age);
        this.runSpeed = runSpeed;
    }
}

const hawk = new Hawk("Hawk", 8, 70);
const fish = new Fish("Fish", 3, 20);
const rabbit = new Rabbit("Rabbit", 4, 30);

console.log(hawk.name);
console.log(hawk.age);
console.log(hawk.flySpeed);
console.log('\n');

console.log(fish.name);
console.log(fish.age);
console.log(fish.swimSpeed);
console.log('\n');

console.log(rabbit.name);
console.log(rabbit.age);
console.log(rabbit.runSpeed);






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.

// we are not writing getPower or setPower bcz we want power to act as variable.
// user will think power is variable but actually _power is variable.

/* is you make getter and setter with name same as variable, you cannot get it because both function name and
   variable name will be same. So it is recomended that you write variable name with _ and make getters and
   setters without _.
*/
class Car {
    constructor(petrolCapacity) {
        this._petrolCapacity = petrolCapacity;
    }

    get petrolCapacity() {
        return `${this._petrolCapacity} Liters`;
    }

    set petrolCapacity(petrolCapacity) {

        if (petrolCapacity > 50) {
            this._petrolCapacity = 50;
        }
        else if (petrolCapacity < 0) {
            this._petrolCapacity = petrolCapacity;
        }
        else {
            this._petrolCapacity = petrolCapacity;
        }
    }
}

const car = new Car(43);
console.log(car.petrolCapacity);

car.petrolCapacity = 57;
console.log(car.petrolCapacity);

car.petrolCapacity = -7;
console.log(car.petrolCapacity);




35: Instanceof operator:

        It returns true if the object belongs to a class or class inheriting from it.

class Animal {
    constructor(name, age) {
        this.name = name;
        this.age = age;
    }
}

class Hawk extends Animal {
    constructor(name, age, flySpeed) {
        super(name, age);
        this.flySpeed = flySpeed;
    }
}

class Car {
    constructor(model) {
        this.model = model;
    }
}

const animal = new Animal("Animal", 15);
const hawk = new Hawk("Hawk", 8, 70);
const car = new Car("Lambo");

console.log(hawk instanceof Hawk); // true
console.log(hawk instanceof Animal); // true
console.log(hawk instanceof Car); // false






36: Passing object to function:

class Car {
    constructor(name, model, color) {
        this.name = name;
        this.model = model;
        this.color = color;
    }
}

function display(car) {
    console.log(`Name: ${car.name}\nModel: ${car.model}\nColor: ${car.color}`);
}


const car1 = new Car("Ferrari", 2023, "Blue");
const car2 = new Car("Lamborghini", 2015, "Yellow");

display(car1);
console.log('\n');
display(car2);





37: Array of objects:

class Car {
    constructor(name, model, color) {
        this.name = name;
        this.model = model;
        this.color = color;
    }

    display() {
        console.log(`Name: ${this.name}\nModel: ${this.model}\nColor: ${this.color}`);
    }
}


const car1 = new Car("Ferrari", 2023, "Blue");
const car2 = new Car("Lamborghini", 2015, "Yellow");
const car3 = new Car("Corvette", 2022, "Green");

const allCars = [car1, car2, car3]; // making array of all objects


allCars[0].display();
console.log('\n');

allCars[1].display();
console.log('\n');

allCars[2].display();
console.log('\n');

// OR

for (const cars of allCars) {
    cars.display();
    console.log('\n');
}





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.

class Car {
    constructor(name, model, color) {
        this.name = name;
        this.model = model;
        this.color = color;
    }

    display() {
        console.log(`Name: ${this.name}\nModel: ${this.model}\nColor: ${this.color}`);
    }
}


const car1 = new Car("Ferrari", 2023, "Blue");
const car2 = new Car("Lamborghini", 2015, "Yellow");
const car3 = new Car("Corvette", 2022, "Green");

const allCars = [car1, car2, car3]; // making array of all objects


allCars[0].display();
console.log('\n');

allCars[1].display();
console.log('\n');

allCars[2].display();
console.log('\n');

// OR

for (const cars of allCars) {
    cars.display();
    console.log('\n');
}





39: Simple Garage System:

class Car {
    constructor(name, model, color, id) {
        this.name = name;
        this.model = model;
        this.color = color;
        this.id = id;
    }

    display() {
        console.log(`Name: ${this.name}\nModel: ${this.model}\nColor: ${this.color}\nID: ${this.id}\n`);
    }
}

class Stack {
    allCars = [];

    addCar(name, model, color, id) {
        this.allCars.push(new Car(name, model, color, id));
    }

    removeCar(id) {
        for (let i = 0; i < this.allCars.length; i++) {

            if (this.allCars[i].id == id) {
                this.allCars.splice(i, i);
            }
        }
    }

    displayAllCars() {
        for (const cars of this.allCars) {
            cars.display();
        }
    }

    displayCarById(id) {
        for (let i = 0; i < this.allCars.length; i++) {

            if (this.allCars[i].id == id) {
                this.allCars[i].display();
            }
        }
    }

}

const stack = new Stack;

stack.addCar("Ferrari", 2023, "Blue", "FDA 6564");
stack.addCar("Lamborghini", 2015, "Yellow", "GFD 4653");
stack.addCar("Corvette", 2022, "Green", "FAS 4236");

stack.displayAllCars();

stack.removeCar("GFD 4653");
stack.displayAllCars();

console.log(`Displaying car by ID: `);
stack.displayCarById("FAS 4236");



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.

  1. Try: Use try block to wrap the dangerous code.
  2. Catch: Use catch to handel the error.
  3. Throw: Use throw to throw a user-defined error. Mostly used at places when something will go wrong and wont cause an error.
  4. Finally: Use finally to represent the block of code that will execute regradless of these is an error or not.

try {
    let x = window.prompt("Enter a number: ");
    x = Number(x);

    if (isNaN(x)) { throw "This is not a number!"; }
    if (x == "") { throw "That was empty!"; }

    console.log(`${x} is a number`);

} catch (error) {
    console.log(error);
}
finally {
    console.log("This will always execute");
}



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.

  1. 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 ( () => {} ).
  2. The second argument is the number of milliseconds after which the block is executed.
If you want to stop the execution of setTimeout, you can do clearTimeout( ) and pass the name of the variable in which you have stored the setTimeout( ) method.

HTML:

<head>
    <title>Document</title>
    <style>
        button:hover {
            background: #000;
            color: white;
        }
    </style>
</head>

<body style="display: flex;flex-direction:column;align-items: center; height: 50vh;">
    <button id="button" style="padding: 1rem 2rem;font-size: 1.5rem;border-radius: 1rem; cursor: pointer;">Buy</button>
    <h1 id="message"></h1>
    <script src="index.js"></script>
</body>

JS:

function message1() { document.getElementById("message").innerHTML = "Buy this course for $500!" }
function message2() { document.getElementById("message").innerHTML = "This is not a scam!" }
function message3() { document.getElementById("message").innerHTML = "Do It!" }

const timer1 = setTimeout(message1, 2500);
const timer2 = setTimeout(message2, 5000);
const timer3 = setTimeout(message3, 7500);

document.getElementById("button").onclick = () => {
    clearTimeout(timer1);
    clearTimeout(timer2);
    clearTimeout(timer3);

    document.getElementById("message").innerHTML = "Thanks for buying this Course!";
}



42: setInterval( ):

        This invokes the function repeatedly after a set number of milliseconds. 
This is also an asynchronous function (doesn't pause execution)

clearInterval( ) is used to stop this from executing.

HTML:

<head>
    <title>Document</title>
    <style>
        body {
            display: flex;
            flex-direction: column;
            align-items: center;
            height: 50vh;
        }

        button {
            padding: 1rem 2rem;
            font-size: 1.5rem;
            border-radius: 1rem;
            cursor: pointer;
        }

        button:hover {
            background: #000;
            color: white;
        }
    </style>
</head>

<body>
    <div>
        <button id="start">Start</button>
        <button id="reset">Reset</button>
        <button id="stop">Stop</button>
    </div>
    <h1 id="message"></h1>
    <script src="index.js"></script>
</body>

JS:

let count = 0; // number shown on screen
let timer; // container to store setInterval
let pause = true; // made to run setInterval() function only once even if the start button is pressed multiple times, otherwise, milli-seconds will keep on adding and speed will increase


function increase() {
    document.getElementById("message").innerHTML = count;
    count += 1;
}

document.getElementById("start").onclick = () => {
    if (pause) {
        timer = setInterval(increase, 300);// after 300, you can also pass some arguments you wanna pass to increase function
        pause = false;
    }
}

document.getElementById("stop").onclick = () => {
    clearInterval(timer);
    pause = true;
}

document.getElementById("reset").onclick = () => {
    count = 0;
    document.getElementById("message").innerHTML = count;
}




43: Date Object:

        Date is an object that has many getters and setters function for elements like date and time


// making date object and showing current date, time, time zone
let date = new Date();
console.log("Default date object: ", date, '\n'); // Sat Dec 30 2023 23:57:28 GMT+0500 (Pakistan Standard Time)

// conveting to more readable form (date + time)
let dateNtime = date.toLocaleString();
console.log("Readale date and time format: ", dateNtime, '\n'); // 30/12/2023, 11:57:28 pm

// conveting to more readable form (date only)
let dateOnly = date.toLocaleDateString();
console.log("Readale date format: ", dateOnly, '\n'); // 30/12/2023

// // conveting to more readable form (time only)
let timeOnly = date.toLocaleTimeString();
console.log("Readale time format: ", timeOnly, '\n'); // 11:57:28 pm

// default date
let defaultDate = new Date(0);
defaultDate = defaultDate.toLocaleString();
console.log("Default date: ", defaultDate, '\n'); // 01/01/1970, 5:00:00 am

// add these number of milliseconds to default date
let incDefaultDate = new Date(1000000000000);
incDefaultDate = incDefaultDate.toLocaleString();
console.log("Increased Default date: ", incDefaultDate, '\n'); // 09/09/2001, 6:46:40 am

// year, month, date, hour, minutes, seconds, milliseconds (months start from 0)
let newDate = new Date(2022, 4, 24, 7, 52, 35, 89);
newDate = newDate.toLocaleString();
console.log("New Default date: ", newDate, '\n'); // 24/05/2022, 7:52:35 am

// date time am/pm
let stringNewDate = new Date("Feburary 5, 2023 8:45:23 pm");
stringNewDate = stringNewDate.toLocaleString();
console.log("String New Default date: ", stringNewDate, '\n'); // 05/02/2023, 8:45:23 pm


// ----( Getters )----
// get current year
let year = date.getFullYear();
console.log("Current Full year: ", year, '\n'); // 2023

// get current month
let month = date.getMonth();
console.log("Current Month: ", month + 1, '\n'); // 12

// get current day of month (date)
let dayOfMonth = date.getDate();
console.log("Current Day of Month: ", dayOfMonth, '\n'); // 30

// get current day of week (day)
let dayOfWeek = date.getDay();
console.log("Current Day of Week: ", dayOfWeek, '\n'); // 6

// get current hour
let hour = date.getHours();
console.log("Current Hour: ", hour, '\n'); // 23

// get current minutes
let minutes = date.getMinutes();
console.log("Current Minutes: ", minutes, '\n'); // 57

// get current seconds
let seconds = date.getSeconds();
console.log("Current Seconds: ", seconds, '\n'); // 28

// get current milliseconds
let milliSeconds = date.getMilliseconds();
console.log("Current MilliSeconds: ", milliSeconds, '\n'); // 716


// ----( Setters )----
date.setFullYear(2022);
date.setMonth(10 - 1);
date.setDate(25);
date.setHours(13);
date.setMinutes(35);
date.setSeconds(59);
date.setMilliseconds(345);
let modifiedDate = date.toLocaleString();
console.log("Modified date by setters: ", modifiedDate, '\n'); // 25/10/2022, 1:35:59 pm

function formatDate() {
    let year = date.getFullYear();
    let month = date.getMonth();
    let dayOfMonth = date.getDate();

    return `${dayOfMonth}-${month}-${year}`;
}
console.log("Formatted date: ", formatDate(), '\n'); // 25-9-2022

function formatTime() {
    let hour = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let amORpm = hour >= 12 ? "am" : "pm";
    hour = (hour % 12) || 12; // convert hour from 24 to 12 and if 0 then also 12

    return `${hour}::${minutes}::${seconds} ${amORpm}`;
}
console.log("Formatted time: ", formatTime(), '\n'); // 1::35::59 am



44: Simple Clock:


HTML:

<body>
    <h1 id="message"></h1>
    <script src="index.js"></script>
</body>

JS:

const lable = document.getElementById("message");

update();
setInterval(update, 1000);


function update() {
    let date = new Date();
    let hour = date.getHours();
    let minutes = date.getMinutes();
    let seconds = date.getSeconds();
    let amORpm = hour >= 12 ? "am" : "pm";
    hour = (hour % 12) || 12; // convert hour from 24 to 12 and if 0 then also 12
    hour = formatZeros(hour);
    minutes = formatZeros(minutes);
    seconds = formatZeros(seconds);

    lable.innerHTML = `${hour}:${minutes}:${seconds} ${amORpm}`;
}
function formatZeros(time) {

    time = time.toString();
    return time.length < 2 ? "0" + time : time;
}



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.
Asynchronous Code:

  • Out of sequence.
  • Start now, and finish sometime later.
  • Ex. Access a database, fetch a file, task that takes some time.

console.log("Start of synchronous code");
console.log("Executions of synchronous code");
console.log("End of synchronous code\n");

console.log("Start of asynchronous code");
setTimeout(() => { console.log("Executions of asynchronous code"); }, 3000);
console.log("End of asynchronous code\n");

// Output:

/*
Start of synchronous code
Executions of synchronous code
End of synchronous code

Start of asynchronous code
End of asynchronous code

Executions of asynchronous code // after 3 seconds
*/




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.
// works fine with synchronous function
console.time(`Time taken to press OK`);
alert(`Press OK button`);
console.timeEnd(`Time taken to press OK`);

// Output:
// Time taken to press OK: 5657.360107421875 ms

// donot work for asynchronous function
console.time(`Time taken to press OK`);
setTimeout(() => { console.log(`Function performed`); }, 4000);
console.timeEnd(`Time taken to press OK`);

// Output:
// Time taken to press OK: 0.070068359375 ms

// Function performed // (after 4 seconds)


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.



47: Immediately Invoked Function Expression (IIFE):

        IIFE is a function that is called immediately as soon as it is defined. You don't have to call it.

Syntax:

// Via function:

(function name(params) {
    // code
})();

// Via arrow function:

((args) => {
    //code
})();

// Via async function:

(async function name(params) {
    // code
})();

// Via async arrow:

(async (args) => {
    //code
})();



49: CallBack Hell (Pyramid of Doom):
            A situation that arises in asynchronous programming when there are multiple nested callbacks, making the code difficult to read and maintain.

It is not a recommended way of handling asynchronous operations in modern JS.

// call order function with a callback of production

/*
  1) Place Order - 2sec delay
 
  --- Production ---
  2) Cut The Fruit - 2sec delay
  3) Add fruit, water and ice to machine - 2sec delay
  4) Start the machine - 1sec
  5) Select Container - 2sec delay
  6) Add Toppings - 3sec
  7) Serve Ice Cream - 2sec delay
 
*/


const stock = {
    holder: ["cone", "cup", "stick"],
    Fruits: ["apple", "mango", "strawbery", "grape", "banana"],
    toppings: ["chocolate", "peanuts", "waffles", "rose syrup", "none"],
    liquid: ["water", "ice"]
}

let order = (holder, fruit, topping, callback) => {
    setTimeout(() => {
        console.log(`Order Placed`);
        callback(holder, fruit, topping);
    }, 2000);
}

const production1 = (holder, fruit, topping) => {
    setTimeout(() => {
        console.log(`${fruit} is sliced`);

        setTimeout(() => {
            console.log(`${fruit}, ${stock.liquid[0]} and ${stock.liquid[1]} added to grinder`);

            setTimeout(() => {
                console.log(`Grinding Machine is started`);

                setTimeout(() => {
                    console.log(`Ice-cream mixture poured in ${holder}`);

                    setTimeout(() => {
                        console.log(`${topping} added as topping`);

                        setTimeout(() => {
                            console.log(`Ice-cream is served`);
                        }, 2000);

                    }, 3000);

                }, 2000);

            }, 1000);

        }, 2000);

    }, 2000);
};

order(stock.holder[0], stock.Fruits[2], stock.toppings[1], production1);



50: Promises:
            To solve the hell created by callback hell, we use promises.

// suppose we are fetching data from database, and it take some time to fetch the data. getDatabyID function of database returns us promise. You want to fetch data only if you got success in fetching previous data. (Don't get all data at sametime).

const dataFound = true; // suppose every data is availible in the database

// this is asynchronous function
const getDataByID = (id) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (dataFound) {
                console.log(`Success! ${id}'s data is found\n`)
                resolve("success"); // message when promise is fulfiled
            } else {
                console.log(`Failure! ${id}'s data not found\n`)
                reject("failure"); // message when promise is not fulfiled
            }
        }, 2000);
    })
}

// dont place ; before any .then()
console.log(`Fetching data1...`);
getDataByID(1)
    .then(() => {
        console.log(`Fetching data2...`);
        return getDataByID(2);              // don't forget return
    })

    .then(() => {
        console.log(`Fetching data3...`);
        return getDataByID(3);
    })

    .then(() => {
        console.log(`Fetching data4...`);
        return getDataByID(4);
    })

    .then((res) => { console.log(res); }) // by default we get resolve message as argument                                             in .then which we can print

    .catch((res) => { console.log(res); }) // by default we get reject message as argument                                               in .catch which we can print

    .finally(() => {
        console.log(`Function Completed`); // this will always print
    })


51: Async-Await:

Async function is an asynchronous function that always returns a promise.

Await means that the compiler will wait before executing next statement.

// suppose we are fetching data from database, and it take some time to fetch the data. getDatabyID function of database returns us promise. You want to fetch data only if you got success in previous data. (Don't get all data at sametime).

const dataFound = true; // suppose every data is availible in the database

// this is asynchronous function
const getDataByID = (id) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (dataFound) {
                console.log(`Success! ${id}'s data is found\n`)
                resolve("success"); // message when promise is fulfiled
            } else {
                console.log(`Failure! ${id}'s data not found\n`)
                reject("failure");
            }
        }, 2000);
    })
}

async function getAllData() {
    console.log(`Fetching Data1...`);
    await getDataByID(1);            // await means compiler will wait for completion of this function

    console.log(`Fetching Data2...`);
    await getDataByID(2);

    console.log(`Fetching Data3...`);
    await getDataByID(3);

    console.log(`Fetching Data4...`);
    await getDataByID(4);

    console.log(`Success`);
};

getAllData();

problem that occurs is that we have to call this async function, it will not execute on its own but to make it run on its own, you can make it IFFE ie:

(async function getAllData() {
    console.log(`Fetching Data1...`);
    await getDataByID(1);          

    console.log(`Fetching Data2...`);
    await getDataByID(2);

    console.log(`Fetching Data3...`);
    await getDataByID(3);

    console.log(`Fetching Data4...`);
    await getDataByID(4);

    console.log(`Success`);
})();

To catch errors, you can use try catch:

// suppose we are fetching data from database, and it take some time to fetch the data. getDatabyID function of database returns us promise. You want to fetch data only if you got success in previous data. (Don't get all data at sametime).

const dataFound = false; // suppose every data is not availible in the database

// this is asynchronous function
const getDataByID = (id) => {
    return new Promise((resolve, reject) => {
        setTimeout(() => {
            if (dataFound) {
                console.log(`Success! ${id}'s data is found\n`)
                resolve("success"); // message when promise is fulfiled
            } else {
                console.log(`Failure! ${id}'s data not found`)
                reject("failure");
            }
        }, 2000);
    })
}

(async function getAllData() {

    try {
        console.log(`Fetching Data1...`);
        await getDataByID(1);

    } catch (res) {
        console.log(res, '\n');
    }

    try {
        console.log(`Fetching Data2...`);
        await getDataByID(2);

    } catch (res) {
        console.log(res, '\n');
    }

    try {
        console.log(`Fetching Data3...`);
        await getDataByID(3);

    } catch (res) {
        console.log(res, '\n');
    }

    try {
        console.log(`Fetching Data4...`);
        await getDataByID(4);

    } catch (res) {
        console.log(res, '\n');
    }

    console.log(`Function Complete`);
})();

// dataFound is false and we didn't get error stopping program because of catch



52: DOM (Document Object Model):

  • 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.


53: Select Elements in a webpage:


a) Getting element by ID:

    <h1 id="myHeading"></h1>
    <script>
        const heading = document.getElementById("myHeading");
        heading.innerHTML = "This is a heading";
        heading.style.backgroundColor = "red";
        heading.style.color = "yellow";
    </script>

b) Getting element by Name:
        This is useful if you have several elements with the same name. This tag returns a node list which acts as an array.
If many radio inputs have the same name, you can only select one of them at a time and you can also check which one is selected using forEach.

<input type="radio" name="fruit" value="apple">
    <label for="apple">Apple</label><br>

    <input type="radio" name="fruit" value="mango">
    <label for="mango">Mango</label><br>

    <input type="radio" name="fruit" value="orange" checked>
    <label for="orange">Orange</label><br>

    <script>
        let allFruits = document.getElementsByName("fruit");

        allFruits.forEach(element => {
            if (element.checked) {
                console.log(element.value);
            }
        });
    </script>

c) Getting element by Tag name:
        It returns an HTML list of all elements with specific tag name.

    <ul>
        <li>Orange</li>
        <li>Mango</li>
        <li>Banana</li>
    </ul>

    <script>
        const allFruits = document.getElementsByTagName("li");
        for (let i = 0; i < allFruits.length; i++) {
            console.log(allFruits[i].innerHTML);
        }
    </script>

d) Getting element by class name:
        Returns a list of elements containing a specific class.

    <h1 class="under">Apple</h1>
    <h1 class="over">Mango</h1>
    <h1 class="under">Orange</h1>
    <h1 class="over">Banana</h1>

    <script>
        const underline = document.getElementsByClassName("under");

        for (const element of underline) {
            element.style.textDecoration = "underline";
        }
    </script>


e) Query Selector:
        You can only select one element using the query selector.

document.querySelector(".fruits") // select class
document.querySelector("#apple") // select id
document.querySelector("li") // select tag name
document.querySelector("[li]") // first element with li attribute in whole DOM

e) Query Selector All:
        Select all lists of items containing that specific class, id, tag name etc.

    <h1 class="under">Apple</h1>
    <h1 class="over">Mango</h1>
    <h1 class="under">Orange</h1>
    <h1 class="over">Banana</h1>

    <script>
        const underline = document.querySelectorAll(".under");
        for (const element of underline) {
            element.style.textDecoration = "underline";
        }
    </script>



54: DOM traversal techniques:

<section id="group">

        <ul id="fruits">
            <li>Apple</li>
            <li>Orange</li>
            <li>Banana</li>
        </ul>

        <ul id="veges">
            <li>Potato</li>
            <li>Onion</li>
            <li>Carrot</li>
        </ul>

        <ul id="fast food">
            <li>Ice cream</li>
            <li>Cake</li>
            <li>Coffee</li>
        </ul>

    </section>
  1. .firstElementChild: gives the first child of the list.
    document.querySelector("#veges").firstElementChild.style.backgroundColor = "yellow";

  2. .lastE1ementChild: gives the last child of the list.
    document.querySelector("#veges").lastElementChild.style.backgroundColor = "yellow";

  3. .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";

  4. .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";

  5. .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";

  6. 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"; });


55: Change text of HTML element:

        There are two ways of changing the text content of HTML element.
  1. 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>

  2. .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>



56: Add an HTML element without HTML tag:

  1. 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>



  2. 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>

  3. 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:

    <h1 id="text">This is a Heading</h1>
    <script>
        const heading = document.getElementById("text");

        heading.style.backgroundColor = "black"; // normal color
        heading.style.color = "#3ec6ec"; // hex
        heading.style.fontFamily = "consolas";
        heading.style.textAlign = "center";
        heading.style.border = "8px solid rgb(62, 198, 236)"; // rgb
        // heading.style.display = "none"; // hide element
        heading.style.display = "block"; // show element
    </script>



58: Events:

        An event is an action that occurs as per the user's instruction as input and gives the output in response.

    <div id="box" style="background-color: aqua;width: 8rem;height: 8rem;"></div>
    <script>
        const box = document.getElementById("box");

        function makeRed() {
            box.style.backgroundColor = "red";
        }
        function makeBlue() {
            box.style.backgroundColor = "aqua";
        }
    </script>

All of the following tags take callback, don't add ( ) with the function name, or else it won't work.
  1. .onclick: perform something when the element is clicked.
        const box = document.getElementById("box");
        box.onclick = makeRed;
    This will also work:
    <div id="box" onclick="makeRed()" style="background-color: aqua;width: 8rem;height: 8rem;"></div>
     
  2. .onload: perform something when the element is loaded with web page.
        const box = document.getElementById("box");
        box.onload = window.prompt("Hello");

  3. .onmouseover: performs something when the mouse cursor is over the element.
        let box = document.getElementById("box");
        box.onmouseover = makeRed;

  4. .onmouseout: performs something when the mouse cursor leaves the element.
        let box = document.getElementById("box");
        box.onmouseover = makeRed;
        box.onmouseout = makeBlue;

  5. .onmousedown: performs something while the element is clicked.
        let box = document.getElementById("box");
        box.onmousedown = makeRed;

  6. .onmouseup:
        let box = document.getElementById("box");
        box.onmousedown = makeRed;
        box.onmouseup = makeBlue;



59: Event Listeners:

.addEventListener(event, function, useCapture)
        
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

  1. First, you can pass which event should you handle.
  2. Secondly, which function is called when that event occurs. 
  3. 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.
<head>
    <title>Website</title>
    <style>
        #inner {
            background-color: aqua;
            width: 8rem;
            height: 8rem;
            border: 2px solid black;
        }

        #outer {
            background-color: yellow;
            width: 16rem;
            height: 16rem;
            border: 2px solid red;
            display: flex;
            align-items: center;
            justify-content: center;
        }
    </style>
</head>

<body>
    <div id="outer">
        <div id="inner"></div>
    </div>

    <script>
        let funcCall = 0;
        let inner = document.getElementById("inner");
        let outer = document.getElementById("outer");

        inner.addEventListener("click", makeBlue);
        outer.addEventListener("click", makeBlue, true);

        function makeBlue() {
            if (++funcCall < 2) {
                alert(`${this.id} is preformed first`);
            }
            this.style.backgroundColor = "blue";
        }
    </script>
   
</body>


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.
Display:

<head>
    <title>Website</title>
    <style>
        #myButton {
            font-size: x-large;
            padding: 1rem 2rem;
            margin-bottom: 2rem;
            cursor: pointer;
        }
    </style>
</head>

<body>

    <button id="myButton">Toggle</button><br>
    <img id="myImg" style="width: 30rem;display: none;"
        src="https://carwow-uk-wp-3.imgix.net/New-Lamborghini-Revuelto-doors-1.png? auto=format&cs=tinysrgb&fit=crop&h=800&ixlib=rb-1.1.0&q=60&w=1600">
    <p style="font-size: xx-large;">Click the button!</p>

    <script>
        const button = document.getElementById("myButton");
        const img = document.getElementById("myImg");

        button.addEventListener("click", () => {
            if (img.style.display == "none") {
                img.style.display = "block";
            } else {
                img.style.display = "none";
            }
        })
    </script>

</body>

Visibility:

<head>
    <title>Website</title>
    <style>
        #myButton {
            font-size: x-large;
            padding: 1rem 2rem;
            margin-bottom: 2rem;
            cursor: pointer;
        }
    </style>
</head>

<body>

    <button id="myButton">Toggle</button><br>
    <img id="myImg" style="width: 30rem;visibility: hidden;"
        src="https://carwow-uk-wp-3.imgix.net/New-Lamborghini-Revuelto-doors-1.png? auto=format&cs=tinysrgb&fit=crop&h=800&ixlib=rb-1.1.0&q=60&w=1600">
    <p style="font-size: xx-large;">Click the button!</p>

    <script>
        const button = document.getElementById("myButton");
        const img = document.getElementById("myImg");

        button.addEventListener("click", () => {
            if (img.style.visibility == "hidden") {
                img.style.visibility = "visible";
            } else {
                img.style.visibility = "hidden";
            }
        })
    </script>

</body>


61: Detect key press:

Following are types of key events:
  • keydown
  • kepress
  • keyup

Detect which key is pressed:
<head>
    <title>Website</title>
    <style>
        #myButton {
            font-size: x-large;
            padding: 1rem 2rem;
            cursor: pointer;
        }
    </style>
</head>

<body>
    <h1>Press the button and write something</h1>
    <button id="myButton">Toggle</button>
    <h1 id="text"></h1>

    <script>
        let text = document.getElementById("text");
        const button = document.getElementById("myButton");
        let status = false;

        button.addEventListener("click", () => { status = !status; })
        window.addEventListener("keydown", (event) => {
            if (status) {
                text.textContent = event.key + " is pressed";
            }
        })

    </script>
</body>

Make a box moveable with arrow keys:
<head>
    <title>Website</title>
    <style>
        #myButton {
            font-size: x-large;
            padding: 1rem 2rem;
            cursor: pointer;
            margin-bottom: 1rem;
        }

        #box {
            width: 8rem;
            height: 8rem;
            background-color: aqua;
            border: 2px solid black;
        }
    </style>
</head>

<body>
    <div id="box" style="position: relative;"></div>
    <h1 id="text"></h1>
    <button id="myButton">Toggle</button>
    <h1>Press the button and move the box with arrow keys</h1>

    <script>
        let text = document.getElementById("text");
        let box = document.getElementById("box");
        const button = document.getElementById("myButton");
        let status = false;
        let x = 0;
        let y = 0;
        button.addEventListener("click", () => { status = !status; })
        window.addEventListener("keydown", (event) => {
            if (status) {
                text.textContent = event.key + " is pressed";
            }
        })

        window.addEventListener("keydown", (event) => {
            if (status) {
                switch (event.key) {
                    case "ArrowUp":
                        y -= 5;
                        box.style.top = y + "px";
                        break;
                    case "ArrowDown":
                        y += 5;
                        box.style.top = y + "px";
                        break;
                    case "ArrowLeft":
                        x -= 5;
                        box.style.left = x + "px";
                        break;
                    case "ArrowRight":
                        x += 5;
                        box.style.left = x + "px";
                        break;

                    default:
                        break;
                }
            }
        })

    </script>
</body>

















Comments

Popular posts from this blog

3: HTML blog's visual content with source code

Bootstrap whole in one