This Javascript Cheatsheet is For You!

    JavaScript Basics


    Set of JavaScript basic syntax to add, execute and write basic programming paradigms in Javascript.

  1. On Page Script : Adding internal JavaScript to HTML
    <script type="text/javascript"> //JS code goes here </script>

  2. External JS File : Adding external JavaScript to HTML
    <script src="filename.js"></script>

  3. JavaScript Comments : JavaScript comments can be used to explain JavaScript code, and to make it more readable.

    JavaScript comments can also be used to prevent execution, when testing alternative code.

    Single Line Comments
    <script>
    //Single Line Comment
    </script>

    Multi-line Comments
    <p id="myP"></p>
    <script>
    /*
    The code below will change
    the heading with id = "myH"
    and the paragraph with id = "myP"
    */
    document.getElementById("myP").innerHTML = "My first paragraph.";
    </script>

  4. JavaScript Output

    Using innerHTML : The id attribute defines the HTML element. The innerHTML property defines the HTML content:

    To access an HTML element, JavaScript can use the document.getElementById(id) method.
    <h2>My First Web Page</h2>
    <p>My First Paragraph.</p>
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = 5 + 6;
    </script>
    Note : Changing the innerHTML property of an HTML element is a common way to display data in HTML.

    Using document.write()
    <p>Never call document.write after the document has finished loading.It will overwrite the whole document.</p>
    
    <script>
    document.write(5 + 6);
    </script>
    Note : Using document.write() after an HTML document is loaded, will delete all existing HTML:

    The document.write() method should only be used for testing.

    Using window.alert()
    <h2>alert</h2>
    <p>My first alert message.</p>
    
    <script>
    window.alert(5 + 6);
    </script>
    Note : You can skip the window keyword.

    In JavaScript, the window object is the global scope object. This means that variables, properties, and methods by default belong to the window object. This also means that specifying the window keyword is optional:

    Using console.log()
    <h2>Activate Debugging</h2>
    <p>F12 on your keyboard will activate debugging.</p>
    <p>Then select "Console" in the debugger menu.</p>
    <p>Then click Run again.</p>
    
    <script>
    console.log(5 + 6);
    </script>
    Note : For debugging purposes, you can call the console.log() method in the browser to display data.

    JavaScript Print
    <h2>The window.print() Method</h2>
    
    <p>Click the button to print the current page.</p>
    
    <button onclick="window.print()">Print this page</button>
    Note : JavaScript does not have any print object or print methods.

    You cannot access output devices from JavaScript.

    The only exception is that you can call the window.print() method in the browser to print the content of the current window.

  5. JavaScript Variables : Variables are Containers for Storing Data.

    JavaScript Variables can be declared in 4 ways:
    Automatically
    Using var
    Using let
    Using const

    When to Use var, let, or const?
    Always declare variables
    Always use const if the value should not be changed
    Always use const if the type should not be changed (Arrays and Objects)
    Only use let if you can't use const
    Only use var if you MUST support old browsers.

    Automatically
    <p id="demo"></p>
    
    <script>
    x = 5;
    y = 6;
    z = x + y;
    document.getElementById("demo").innerHTML =
    "The value of z is: " + z;
    </script>
    Note :- It's a good programming practice to declare all variables at the beginning of a script.

    Using var Variables declared with the var keyword can NOT have block scope.
    Variables declared inside a { } block can be accessed from outside the block.
    Redeclaring a variable using the var keyword can impose problems.
    Redeclaring a variable inside a block will also redeclare the variable outside the block:
    <p id="demo"></p>
    
    <script>
    var x = 5;
    var y = 6;
    var z = x + y;
    document.getElementById("demo").innerHTML =
    "The value of z is: " + z;
    </script>
    Note :- The var keyword was used in all JavaScript code from 1995 to 2015.
    The let and const keywords were added to JavaScript in 2015.
    The var keyword should only be used in code written for older browsers.

    Using let The let keyword was introduced in ES6 (2015)
    Variables defined with let cannot be Redeclared
    Variables defined with let must be Declared before use
    Variables defined with let have Block Scope
    Variables defined with let can not be redeclared.
    You can not accidentally redeclare a variable declared with let.
    <p id="demo"></p>
    
    <script>
    let x = 5;
    let y = 6;
    let z = x + y;
    document.getElementById("demo").innerHTML =
    "The value of z is: " + z;
    </script>

    Using const The const keyword was introduced in ES6 (2015)
    Variables defined with const cannot be Redeclared
    Variables defined with const cannot be Reassigned
    Variables defined with const have Block Scope
    A const variable cannot be reassigned:
    JavaScript const variables must be assigned a value when they are declared:
    <p id="demo"></p>
    
    <script>
    const x = 5;
    const y = 6;
    const z = x + y;
    document.getElementById("demo").innerHTML =
    "The value of z is: " + z;
    </script>
    Note :- When to use JavaScript const?
    Always declare a variable with const when you know that the value should not be changed.

    Use const when you declare:
    A new Array
    A new Object
    A new Function
    A new RegExp

  6. JavaScript Data Types : A JavaScript variable can hold any type of data.
    In programming, data types is an important concept.
    To be able to operate on variables, it is important to know something about the type.

    JavaScript has 8 Datatypes

    String
    Number
    Bigint
    Boolean
    Undefined
    Null
    Symbol
    Object

    The Object Datatype
    The object data type can contain:

    An object
    An array
    A date
    <script>
    // Numbers:
    let length = 16;
    let weight = 7.5;
    
    // Strings:
    let color = "Yellow";
    let lastName = "Johnson";
    
    // Booleans
    let x = true;
    let y = false;
    
    // Object:
    const person = {firstName:"John", lastName:"Doe"};
    
    // Array object:
    const cars = ["Saab", "Volvo", "BMW"];
    
    // Date object:
    const date = new Date("2022-03-25");
    </script>

    JavaScript Strings : A string (or a text string) is a series of characters like "Kaushal Jacker".

    Strings are written with quotes. You can use single or double quotes:

    You can use quotes inside a string, as long as they don't match the quotes surrounding the string:
    <p id="demo"></p>
    
    <script>
    let carName1 = "Volvo XC60";
    let carName2 = 'Volvo XC90';
    let answer1 = "It's alright";
    
    document.getElementById("demo").innerHTML =
    carName1 + "<br>" + 
    carName2 + "<br>" + 
    answer1; 
    </script>
    Note :- When adding a number and a string, JavaScript will treat the number as a string.

    JavaScript Numbers : All JavaScript numbers are stored as decimal numbers (floating point).

    Numbers can be written with, or without decimals:
    <p id="demo"></p>
    
    <script>
    let x1 = 34.00;
    let x2 = 34;
    let x3 = 3.14;
    
    document.getElementById("demo").innerHTML =
    x1 + "<br>" + x2 + "<br>" + x3;
    </script>
    Note :- Most programming languages have many number types:
    Whole numbers (integers):
    byte (8-bit), short (16-bit), int (32-bit), long (64-bit)
    Real numbers (floating-point):
    float (32-bit), double (64-bit).
    Javascript numbers are always one type:
    double (64-bit floating point).

    JavaScript BigInt : All JavaScript numbers are stored in a a 64-bit floating-point format.

    JavaScript BigInt is a new datatype (ES2020) that can be used to store integer values that are too big to be represented by a normal JavaScript Number.
    <p id="demo"></p>
    
    <p>You cannot perform math between a BigInt type and a Number type.</p>
    
    <script>
    let x = BigInt("123456789012345678901234567890");
    document.getElementById("demo").innerHTML = x; 
    </script>

    JavaScript Booleans : Booleans can only have two values: true or false.
    <p id="demo"></p>
    
    <script>
    let x = 5;
    let y = 5;
    let z = 6;
    
    document.getElementById("demo").innerHTML =
    (x == y) + "<br>" + (x == z);
    </script>
    Note :- Booleans are often used in conditional testing.

    Undefined : In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

    Any variable can be emptied, by setting the value to undefined. The type will also be undefined.
    <p id="demo"></p>
    
    <script>
    let car = "Volvo";
    car = undefined;
    
    document.getElementById("demo").innerHTML = car + "<br>" + typeof car;
    </script>

  7. Functions : A JavaScript function is a block of code designed to perform a particular task.

    A JavaScript function is executed when "something" invokes it (calls it).

    A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

    Function names can contain letters, digits, underscores, and dollar signs (same rules as variables).

    The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...)

    The code to be executed, by the function, is placed inside curly brackets: {}
    <h1>JavaScript Functions</h1>
    <p>Call a function which performs a calculation and returns the result:</p>
    <p id="demo"></p>
    
    <script>
    function myFunction(p1, p2) {
    return p1 * p2;
    }
    
    let result = myFunction(4, 3);
    document.getElementById("demo").innerHTML = result;
    </script>

    JavaScript Arrow Function : Arrow functions were introduced in ES6.

    Arrow functions allow us to write shorter function syntax:
    <p id="demo"></p>
    
    <script>
    let hello = "";
    
    hello = () => {
    return "Hello World!";
    }
    
    document.getElementById("demo").innerHTML = hello();
    </script>

  8. Conditional Statements : Conditional statements are used to perform operations based on some conditions.

    In JavaScript we have the following conditional statements:
    Use if to specify a block of code to be executed, if a specified condition is true
    Use else to specify a block of code to be executed, if the same condition is false
    Use else if to specify a new condition to test, if the first condition is false
    Use switch to specify many alternative blocks of code to be executed

    If Statement : The block of code to be executed, when the condition specified is true..

    Use the if statement to specify a block of JavaScript code to be executed if a condition is true.
    if (condition) {
    // block of code to be executed if the condition is true
    }
    Note :- if is in lowercase letters. Uppercase letters (If or IF) will generate a JavaScript error.

    Example:
    <p id="demo">Good Evening!</p>
    
    <script>
    let x = 2;
    if (x < 18) {
    document.getElementById("demo").innerHTML = "Good day!";
    }
    </script>

    If-else Statement : If the condition for the if block is false, then the else block will be executed.
    if (condition) {
    // block of code to be executed if the condition is true
    } else {
    // block of code to be executed if the condition is false
    }
    Example:
    <p id="demo"></p>
    
    <script>
    const hour = new Date().getHours(); 
    let greeting;
    
    if (hour < 18) {
    greeting = "Good day!!!!";
    } else {
    greeting = "Good evening!!!!";
    }
    
    document.getElementById("demo").innerHTML = greeting;
    </script>

    Else-if Statement : A basic if-else ladder
    if (condition1) {
    // block of code to be executed if condition1 is true
    } else if (condition2) {
    // block of code to be executed if the condition1 is false and condition2 is true
    } else {
    // block of code to be executed if the condition1 is false and condition2 is false
    }
    Example:
    <p id="demo"></p>
    
    <script>
    const time = new Date().getHours();
    let greeting;
    if (time < 10) {
    greeting = "Good morning";
    } else if (time < 20) {
    greeting = "Good day";
    } else {
    greeting = "Good evening";
    }
    document.getElementById("demo").innerHTML = greeting;
    </script>

    Switch Statement : The switch statement is used to perform different actions based on different conditions.

    Use the switch statement to select one of many code blocks to be executed.

    This is how it works:
    The switch expression is evaluated once.
    The value of the expression is compared with the values of each case.
    If there is a match, the associated block of code is executed.
    If there is no match, the default code block is executed.
    switch (expression) {
    case value1:
    // code block
    break;
    case value2:
    // code block
    break;
    default:
    // code block
    }
    Example:
    <p id="demo"></p>
    
    <script>
    let day;
    switch (new Date().getDay()) {
    case 0:
    day = "Sunday";
    break;
    case 1:
    day = "Monday";
    break;
    case 2:
    day = "Tuesday";
    break;
    case 3:
    day = "Wednesday";
    break;
    case 4:
    day = "Thursday";
    break;
    case 5:
    day = "Friday";
    break;
    case  6:
    day = "Saturday";
    }
    document.getElementById("demo").innerHTML = "Today is " + day;
    </script>

  9. Iterative Statements (Loops) : Iterative statement facilitates programmer to execute any block of code lines repeatedly and can be controlled as per conditions added by the programmer.

    For Loop : For loop syntax in javascript
    for (initialization; condition; updation) {
    // code block to be executed
    }
    Example :
    for (let i = 0; i < 5; i++) {
    text += "Iteration number: " + i + "
    "; }

    While loop : Runs the code till the specified condition is true
    while (condition) {
    // code block to be executed
    }

    Example :

    <p id="demo"></p>
    
    <script>
    let text = "";
    let i = 0;
    while (i < 10) {
    text += "<br>The number is " + i;
    i++;
    }
    document.getElementById("demo").innerHTML = text;
    </script>

    Do While loop : A do while loop is executed at least once despite the condition being true or false
    do {
    // run this code in block
    i++;
    } while (condition);

    Example :

    <p id="demo"></p>
    
    <script>
    let text = ""
    let i = 0;
    
    do {
    text += "<br>The number is " + i;
    i++;
    }
    while (i < 9);  
    
    document.getElementById("demo").innerHTML = text;
    </script>


  10. Strings : The string is a sequence of characters that is used for storing and managing text data.

    All string methods return a new string. They don't modify the original string.

    Strings are immutable: Strings cannot be changed, only replaced.

    length method : The length property returns the length of a string:
    str.length()

    Example

    <p>The length of the string is:</p>
    <p id="demo"></p>
    
    <script>
    let text = "Kaushal Jacker";
    document.getElementById("demo").innerHTML = text.length;
    </script>
    Note :- JavaScript counts positions from zero.
    First position is 0.
    Second position is 1.

    toUpperCase method : A string is converted to upper case with toUpperCase():
    str.toUpperCase()

    Example

    <button onclick="myFunction()">Try it</button>
    
    <p id="demo">SpecBits!</p>
    
    <script>
    function myFunction() {
    let text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML =
    text.toUpperCase();
    }
    </script>

    toLowerCase method : A string is converted to lower case with toLowerCase():
    str.toLowerCase()

    Example

    <button onclick="myFunction()">Try it</button>
    
    <p id="demo">SpecBits!</p>
    
    <script>
    function myFunction() {
    let text = document.getElementById("demo").innerHTML;
    document.getElementById("demo").innerHTML =
    text.toLowerCase();
    }
    </script>

    charAt method : Returns the character from the specified index.
    str.charAt(3)

    Example

    <p>The charAt() method returns the character at a given position in a string:</p>
    
    <p id="demo"></p>
    
    <script>
    var text = "Kaushal Jacker";
    document.getElementById("demo").innerHTML = text.charAt(2);
    </script>

    concat method : Joins two or more strings together.
    str1.concat(str2)

    Example

    <p id="demo"></p>
    
    <script>
    let text1 = "Hello";
    let text2 = "World!";
    let text3 = text1.concat(" ",text2);
    document.getElementById("demo").innerHTML = text3;
    </script>
    Note :- The concat() method can be used instead of the plus operator.

    slice method : slice() extracts a part of a string and returns the extracted part in a new string.

    The method takes 2 parameters: start position, and end position (end not included).
    str.slice(0,5)

    Example

    <script>
    let text = "Apple, Banana, Kiwi";
    let part = text.slice(7,13);
    document.getElementById("demo").innerHTML = part; 
    </script>

    substring method : Returns a substring of a string containing characters from the specified indices.

    substring() is similar to slice().

    The difference is that start and end values less than 0 are treated as 0 in substring().
    str.substring(0,5)

    Example

    <p id="demo"></p>
    
    <script>
    let str = "Apple, Orange, Kiwi";
    document.getElementById("demo").innerHTML = str.substring(7,13);
    </script>
    Note :- If you omit the second parameter, substring() will slice out the rest of the string.

    substr method : substr() is similar to slice().

    The difference is that the second parameter specifies the length of the extracted part.
    str.substr(2,5)

    Example

    <p id="demo"></p>
    
    <script>
    let str = "Apple, Pineapple, Kiwi";
    document.getElementById("demo").innerHTML = str.substr(7,6);
    </script>
    Note :- If you omit the second parameter, substr() will slice out the rest of the string.
    If the first parameter is negative, the position counts from the end of the string.

    replace method : The replace() method replaces a specified value with another value in a string:
    string.replace(searchValue, newValue)

    Example

    <button onclick="myFunction()">Try it</button>
    
    <p id="demo">Please visit SpecBits and SpecBits!</p>
    
    <script>
    function myFunction() {
    let text = document.getElementById("demo").innerHTML; 
    document.getElementById("demo").innerHTML =
    text.replace("SpecBits","Developersarmy");
    }
    </script>

    To replace case insensitive, use a regular expression with an /i flag (insensitive):
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo">Please visit SpecBits!</p>
    
    <script>
    function myFunction() {
    let text = document.getElementById("demo").innerHTML; 
    document.getElementById("demo").innerHTML =
    text.replace(/SPECBITS/i,"Developersarmy");
    }
    </script>
    Note :- The replace() method does not change the string it is called on.
    The replace() method returns a new string.
    The replace() method replaces only the first match
    If you want to replace all matches, use a regular expression with the /g flag set.
    By default, the replace() method replaces only the first match:

    replaceAll method : In 2021, JavaScript introduced the string method replaceAll():

    The replaceAll() method allows you to specify a regular expression instead of a string to be replaced.

    If the parameter is a regular expression, the global flag (g) must be set, otherwise a TypeError is thrown.
    string.replaceAll(searchValue, newValue)

    Example

    <p id="demo"></p>
    
    <script>
    let text = "I love cats. Cats are very easy to love. Cats are very popular."
    text = text.replaceAll("Cats","Dogs");
    text = text.replaceAll("cats","dogs");
    
    document.getElementById("demo").innerHTML = text;
    </script>
    Note :- replaceAll() is an ES2021 feature.
    replaceAll() does not work in Internet Explorer.

    trim method : The trim() method removes whitespace from both sides of a string:
    string.trim()

    Example

    <p id="demo"></p>
    
    <script>
    let text1 = "     Hello World!     ";
    let text2 = text1.trim();
    
    document.getElementById("demo").innerHTML =
    "Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
    </script>

    trimStart method : ECMAScript 2019 added the String method trimStart() to JavaScript.

    The trimStart() method works like trim(), but removes whitespace only from the start of a string.
    string.trimStart()

    Example

    <p id="demo"></p>
    
    <script>
    let text1 = "     Hello World!     ";
    let text2 = text1.trimStart();
    
    document.getElementById("demo").innerHTML =
    "Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
    </script>

    trimEnd method : ECMAScript 2019 added the string method trimEnd() to JavaScript.

    The trimEnd() method works like trim(), but removes whitespace only from the end of a string.
    string.trimEnd()

    Example

    <p id="demo"></p>
    
    <script>
    let text1 = "     Hello World!     ";
    let text2 = text1.trimEnd();
    
    document.getElementById("demo").innerHTML =
    "Length text1 = " + text1.length + "<br>Length text2 = " + text2.length;
    </script>

    Converting a String to an Array

    split method : A string can be converted to an array with the split() method:

    The split() method splits a string into an array of substrings.

    The split() method returns the new array.

    The split() method does not change the original string.

    If (" ") is used as separator, the string is split between words.
    string.split(separator, limit)
    Note :- separator & limit are Optional.

    Example

    <p id="demo"></p>
    
    <script>
    let text = "a,b,c,d,e,f";
    const myArray = text.split(",");
    document.getElementById("demo").innerHTML = myArray[4];
    </script>
    Note : If the separator is omitted, the returned array will contain the whole string in index [0].
    If the separator is "", the returned array will be an array of single characters:

    String Search :

    indexOf method : The indexOf() method returns the index (position) the first occurrence of a string in a string:
    string.indexOf(searchvalue, start)
    Note :- start is optional
    The position to start from (default is 0).

    Example

    <p>The position of the first occurrence of "locate" is:</p>
    <p id="demo"></p>
    
    <script>
    let text = "Please locate where 'locate' occurs!";
    let index = text.indexOf("locate");
    document.getElementById("demo").innerHTML = index; 
    </script>

    lastIndexOf method : The lastIndexOf() method returns the index of the last occurrence of a specified text in a string:
    string.lastIndexOf(searchvalue, start)
    Note :- start is optional
    The position to start from (default is 0).

    Note :- Both indexOf(), and lastIndexOf() return -1 if the text is not found:

    Example

    <p>The position of the first occurrence of "locate" is:</p>
    <p id="demo"></p>
    
    <script>
    let text = "Please locate where 'locate' occurs!";
    let index = text.lastIndexOf("locate");
    document.getElementById("demo").innerHTML = index;
    </script>

    search method : The search() method searches a string for a string (or a regular expression) and returns the position of the match:
    string.search(searchValue)

    Example

    <p>The position of the first occurrence of "locate" is:</p>
    <p id="demo"></p>
    
    <script>
    let text = "Please locate where 'locate' occurs!";
    let index = text.search("locate");
    document.getElementById("demo").innerHTML = index; 
    </script>
    Note :- The search() method cannot take a second start position argument.

    The indexOf() method cannot take powerful search values (regular expressions).

    match method : The match() method returns an array containing the results of matching a string against a string (or a regular expression).
    string.match(match)

    Example

    <p>Perform a global, case-insensitive search for "ain":</p>
    
    <p id="demo"></p>
    
    <script>
    let text = "The rain in SPAIN stays mainly in the plain"; 
    const myArr = text.match(/ain/gi);
    document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
    </script>
    Note :- If a regular expression does not include the g modifier (global search), match() will return only the first match in the string.

    matchAll method : The matchAll() method returns an iterator containing the results of matching a string against a string (or a regular expression).
    string.matchAll(match)

    Example

    <p>Perform a global, case-insensitive search for "ain":</p>
    
    <p id="demo"></p>
    
    <script>
    let text = "The rain in SPAIN stays mainly in the plain"; 
    const myArr = text.matchAll(/ain/gi);
    document.getElementById("demo").innerHTML = myArr.length + " " + myArr;
    </script>
    Note :- matchAll() is an ES2020 feature.

    matchAll() does not work in Internet Explorer.

    includes method : The includes() method returns true if a string contains a specified value. Otherwise it returns false.
    string.includes(searchvalue, start)
    Note :- start is optional.

    Example

    <p>Check if a string includes "world":</p>
    <p id="demo"></p>
    
    <p>The includes() method is not supported in Internet Explorer.</p>
    
    <script>
    let text = "Hello world, welcome to the universe.";
    document.getElementById("demo").innerHTML = text.includes("world");
    </script>
    Note :- includes() is case sensitive.

    includes() is an ES6 feature.

    includes() is not supported in Internet Explorer.

    startsWith method : The startsWith() method returns true if a string begins with a specified value. Otherwise it returns false:
    string.includes(searchvalue, start)
    Note :- start is optional.

    Example

    <p id="demo"></p>
    
    <p>The startsWith() method is not supported in Internet Explorer.</p>
    
    <script>
    let text = "Hello world, welcome to the universe.";
    document.getElementById("demo").innerHTML = text.startsWith("world", 6);
    </script>
    Note :- startsWith() is case sensitive.

    startsWith() is an ES6 feature.

    startsWith() is not supported in Internet Explorer.

    endsWith method : The endsWith() method returns true if a string ends with a specified value. Otherwise it returns false:
    string.endsWith(searchvalue, length)
    Note :- length is optional.

    Example

    <p id="demo"></p>
    
    <p>The startsWith() method is not supported in Internet Explorer.</p>
    
    <script>
    let text = "Hello world, welcome to the universe.";
    document.getElementById("demo").innerHTML = text.startsWith("world", 6);
    </script>
    Note :- endsWith() is case sensitive.

    endsWith() is an ES6 feature.

    endsWith() is not supported in Internet Explorer.

  11. JavaScript Arrays : The array is a collection of data items of the same type. In simple terms, it is a variable that contains multiple values.

    An array is a special variable, which can hold more than one value:

    eg. const cars = ["Saab", "Volvo", "BMW"];

    An array can hold many values under a single name, and you can access the values by referring to an index number.

    Creating an Array Using an array literal is the easiest way to create a JavaScript Array.
    const array_name = [item1, item2, ...];
    const cars = new Array("Saab", "Volvo", "BMW");
    Note :- It is a common practice to declare arrays with the const keyword.

    Spaces and line breaks are not important. A declaration can span multiple lines:
    eg...
    <p id="demo"></p>
    <script>
    
    const cars = [
    "Saab",
    "Volvo",
    "BMW"
    ];
    document.getElementById("demo").innerHTML = cars;
    </script>

    You can also create an array, and then provide the elements:
    <p id="demo"></p>
    
    <script>
    const cars = [];
    cars[0]= "Saab";
    cars[1]= "Volvo";
    cars[2]= "BMW";
    document.getElementById("demo").innerHTML = cars;
    </script>

    Accessing Array Elements
    <p id="demo"></p>
    
    <script>
    const cars = ["Saab", "Volvo", "BMW"];
    document.getElementById("demo").innerHTML = cars[0];
    </script>
    Note :- Array indexes start with 0.

    [0] is the first element. [1] is the second element.

    Converting an Array to a String : The JavaScript method toString() converts an array to a string of (comma separated) array values.

    JavaScript automatically converts an array to a comma separated string when a primitive value is expected.

    This is always the case when you try to output an array.
    array.toString()
    Note :- All JavaScript objects have a toString() method.

    Example

    <p id="demo"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits.toString();
    </script>

    join method :- The join() method also joins all array elements into a string.

    It behaves just like toString(), but in addition you can specify the separator:
    <p id="demo"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo").innerHTML = fruits.join(" * ");
    </script>

    Arrays are Objects : Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.

    But, JavaScript arrays are best described as arrays.

    Arrays use numbers to access its "elements".
    <p id="demo"></p>
    
    <script>
    const person = {firstName:"John", lastName:"Doe", age:46};
    document.getElementById("demo").innerHTML = person.firstName;
    </script>

    length method :- The length property returns the length (size) of an array:
    <p id="demo"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    let size = fruits.length;
    document.getElementById("demo").innerHTML = size;
    </script>

    Popping and Pushing :- When you work with arrays, it is easy to remove elements and add new elements.

    Popping items out of an array, or pushing items into an array.

    pop method The pop() method removes the last element from an array:
    <p id="demo1"></p>
    <p id="demo2"></p>
                        
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = fruits;
    fruits.pop();
    document.getElementById("demo2").innerHTML = fruits;
    </script>

    The pop() method returns the value that was "popped out":
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const example = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = example.pop();
    document.getElementById("demo2").innerHTML = example;
    </script>

    push method The push() method adds a new element to an array (at the end):
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = fruits;
    fruits.push("Kiwi");
    document.getElementById("demo2").innerHTML = fruits;
    </script>

    The push() method returns the new array length:
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const example = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = example.push("Kiwi");
    document.getElementById("demo2").innerHTML = example;
    </script>

    Shifting Elements :- Shifting is equivalent to popping, but working on the first element instead of the last.

    shift method The shift() method removes the first array element and "shifts" all other elements to a lower index.
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = fruits;
    fruits.shift();
    document.getElementById("demo2").innerHTML = fruits;
    </script>

    The shift() method returns the value that was "shifted out":
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const example = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = example.shift();
    document.getElementById("demo2").innerHTML = example;
    </script>

    unshift method The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements:
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = fruits;
    fruits.unshift("Lemon");
    document.getElementById("demo2").innerHTML = fruits;
    </script>

    The unshift() method returns the new array length:
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const example = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = example.unshift("Lemon");
    document.getElementById("demo2").innerHTML = example;
    </script>

    delete method
    Warning ! Array elements can be deleted using the JavaScript operator delete.

    Using delete leaves undefined holes in the array.

    Use pop() or shift() instead.
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    
    document.getElementById("demo1").innerHTML =
    "The first fruit is: " + fruits[0];
    
    delete fruits[0];
    
    document.getElementById("demo2").innerHTML =
    "The first fruit is: " + fruits[0];
    </script>

    Merging (Concatenating) Arrays The concat() method creates a new array by merging (concatenating) existing arrays:

    Example (Merging Two Arrays)
    <p id="demo"></p>
    
    <script>
    const myGirls = ["Cecilie", "Lone"];
    const myBoys = ["Emil", "Tobias", "Linus"];
    const myChildren = myGirls.concat(myBoys);
    
    document.getElementById("demo").innerHTML = myChildren;
    </script>
    Note :- The concat() method does not change the existing arrays. It always returns a new array.

    The concat() method can take any number of array arguments:

    Example (Merging Three Arrays)
    <p id="demo"></p>
    
    <script>
    const array1 = ["Cecilie", "Lone"];
    const array2 = ["Emil", "Tobias", "Linus"];
    const array3 = ["Robin", "Morgan"];
    
    const result = array1.concat(array2, array3); 
    
    document.getElementById("demo").innerHTML = result;
    </script>
    Note :- The concat() method can also take strings as arguments:

    Flattening an Array Flattening an array is the process of reducing the dimensionality of an array.

    The flat() method creates a new array with sub-array elements concatenated to a specified depth.
    <p id="demo"></p>
    
    <script>
    const myArr = [[1,2],[3,4],[5,6]];
    
    const newArr = myArr.flat();
    document.getElementById("demo").innerHTML = newArr;
    </script>
    Note :- JavaScript Array flat() is supported in all modern browsers since January 2020:

    Splicing and Slicing Arrays The splice() method adds new items to an array.

    The slice() method slices out a piece of an array.

    splice method The splice() method can be used to add new items to an array:
    array.splice(index, howmany, item1, ....., itemX)
    howmany, item1, ....., itemX are optional

    Example
    <p id="demo1"></p>
    <p id="demo2"></p>
    <p id="demo3"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Apple", "Mango"];
    document.getElementById("demo1").innerHTML = "Original Array:<br> " + fruits;
    let removed = fruits.splice(2, 2, "Lemon", "Kiwi"); 
    document.getElementById("demo2").innerHTML = "New Array:<br>" + fruits;
    document.getElementById("demo3").innerHTML = "Removed Items:<br> " + removed; 
    </script>
    Note :- The splice() method returns an array with the deleted items:

    Using splice() to Remove Elements
    array.splice(0, 1);

    slice method The slice() method slices out a piece of an array into a new array.
    array.slice(start, end)
    start & end are optional

    Example
    <p id="demo"></p>
    
    <script>
    const fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
    const citrus = fruits.slice(1);
    document.getElementById("demo").innerHTML = fruits + "<br><br>" + citrus;
    </script>
    Note :- The slice() method creates a new array.

    The slice() method does not remove any elements from the source array.

  12. JavaScript Sorting Arrays : There are no built-in functions for finding the highest or lowest value in a JavaScript array.

    Sorting an Array The sort() method sorts an array alphabetically:
    array.sort();

    Reversing an Array The reverse() method reverses the elements in an array.

    You can use it to sort an array in descending order:
    array.sort();
    array.reverse();

    Numeric Sort
    <p id="demo1"></p>
    <p id="demo2"></p>
    
    <script>
    const points = [40, 100, 1, 5, 25, 10];
    document.getElementById("demo1").innerHTML = points;  
    
    points.sort(function(a, b){return a - b});
    document.getElementById("demo2").innerHTML = points;
    </script>

    Sorting an Array in Random Order
    <button onclick="myFunction()">Click multiple times</button>
    <p id="demo"></p>
    
    <script>
    const points = [40, 100, 1, 5, 25, 10];
    document.getElementById("demo").innerHTML = points;  
    
    function myFunction() {
    points.sort(function(){return 0.5 - Math.random()});
    document.getElementById("demo").innerHTML = points;
    }
    </script>

  13. JavaScript Array Iteration : Array iteration methods operate on every array item.

    forEach() method The forEach() method calls a function (a callback function) once for each array element.
    <p id="demo"></p>
    
    <script>
    const numbers = [45, 4, 9, 16, 25];
    
    let txt = "";
    numbers.forEach(myFunction);
    document.getElementById("demo").innerHTML = txt;
    
    function myFunction(value, index, array) {
    txt += value + "<br>"; 
    }
    </script>
    Note :- When a callback function uses only the value parameter, the index and array parameters can be omitted:

    map() method The map() method creates a new array by performing a function on each array element.

    The map() method does not execute the function for array elements without values.

    The map() method does not change the original array.
    <p id="demo"></p>
    
    <script>
    const numbers = [45, 4, 9, 16, 25];
    
    let txt = "";
    numbers.forEach(myFunction);
    document.getElementById("demo").innerHTML = txt;
    
    function myFunction(value, index, array) {
    txt += value + "<br>"; 
    }
    </script>
    Note :- When a callback function uses only the value parameter, the index and array parameters can be omitted:

    filter() method The filter() method creates a new array with array elements that pass a test.
    <p id="demo"></p>
    
    <script>
    const numbers = [45, 4, 9, 16, 25];
    const over18 = numbers.filter(myFunction);
    
    document.getElementById("demo").innerHTML = over18;
    
    function myFunction(value) {
    return value > 18;
    }
    </script>
    reduce() method The reduce() method runs a function on each array element to produce (reduce it to) a single value.

    The reduce() method works from left-to-right in the array.

    The reduce() method does not reduce the original array.
    <p id="demo"></p>
    
    <script>
    const numbers = [45, 4, 9, 16, 25];
    let sum = numbers.reduce(myFunction);
    
    document.getElementById("demo").innerHTML = "The sum is " + sum;
    
    function myFunction(total, value, index, array) {
    return total + value;
    }
    </script>

    indexOf() method The indexOf() method searches an array for an element value and returns its position.

    Note :- The first item has position 0, the second item has position 1, and so on.
    array.indexOf(item, start)
    start is optional.

    Example
    <p id="demo"></p>
    
    <script>
    const fruits = ["Apple", "Orange", "Apple", "Mango"];
    let position = fruits.indexOf("Apple") + 1;
    
    document.getElementById("demo").innerHTML = "Apple is found in position " + position;
    </script> 
    Note :- Array.indexOf() returns -1 if the item is not found.

    If the item is present more than once, it returns the position of the first occurrence.

    find() method The find() method returns the value of the first array element that passes a test function.

    find() is an ES6 feature (JavaScript 2015).
    array.find(function(currentValue, index, arr),thisValue)
    index is optional.
    arr is optional
    thisValue is optional

    Example
     <p id="demo"></p>
    
    <script>
    const numbers = [4, 9, 16, 25, 29];
    let first = numbers.find(myFunction);
    
    document.getElementById("demo").innerHTML = "First number over 18 is " + first;
    
    function myFunction(value, index, array) {
    return value > 18;
    }
    </script>
    Note :- The findIndex() method returns the index of the first array element that passes a test function.

    Array.from() method The Array.from() method returns an Array object from any object with a length property or any iterable object.

    from() is an ES6 feature (JavaScript 2015).
    Array.from(object, mapFunction, thisValue)
    mapFunction is optional.
    thisValue is optional

    Example
    <p id="demo"></p>
    
    <script>
    const myArr = Array.from("ABCDEFG");
    document.getElementById("demo").innerHTML = myArr;
    </script>
    Note :- from() is not supported in Internet Explorer.

    Spread (...) method The ... operator expands an iterable (like an array) into more elements:

    ... is an ES6 feature (JavaScript 2015).
    <p id="demo"></p>
    
    <script>
    const q1 = ["Jan", "Feb", "Mar"];
    const q2 = ["Apr", "May", "Jun"];
    const q3 = ["Jul", "Aug", "Sep"];
    const q4 = ["Oct", "Nov", "May"];
    
    const year = [...q1, ...q2, ...q3, ...q4];
    document.getElementById("demo").innerHTML = year; 
    </script>
    Note :- ... is not supported in Internet Explorer.

  14. Number Methods :

    toString Method :- The toString() method returns a number as a string.

    All number methods can be used on any type of numbers (literals, variables, or expressions):
    <p id="demo"></p>
    
    <script>
    let x = 123;
    document.getElementById("demo").innerHTML =
    x.toString() + "<br>" +
    (123).toString() + "<br>" +
    (100 + 23).toString();
    </script>

    toExponential Method:- toExponential() returns a string, with a number rounded and written using exponential notation.

    A parameter defines the number of characters behind the decimal point:
    <p id="demo"></p>
    
    <script>
    let x = 9.656;
    document.getElementById("demo").innerHTML =
    x.toExponential() + "<br>" + 
    x.toExponential(2) + "<br>" + 
    x.toExponential(4) + "<br>" + 
    x.toExponential(6);
    </script>
    Note :- The parameter is optional. If you don't specify it, JavaScript will not round the number.

    toFixed Method :- toFixed() returns a string, with the number written with a specified number of decimals:
    <p id="demo"></p>
    
    <script>
    let x = 9.656;
    document.getElementById("demo").innerHTML =
    x.toFixed(0) + "<br>" +
    x.toFixed(2) + "<br>" +
    x.toFixed(4) + "<br>" +
    x.toFixed(6);
    </script>
    Note :- toFixed(2) is perfect for working with money.

    toPrecision Method :- toPrecision() returns a string, with a number written with a specified length:
    <p id="demo"></p>
    
    <script>
    let x = 9.656;
    document.getElementById("demo").innerHTML = 
    x.toPrecision() + "<br>" +
    x.toPrecision(2) + "<br>" +
    x.toPrecision(4) + "<br>" +
    x.toPrecision(6);  
    </script>

    valueOf Method :- valueOf() returns a number as a number.
    <p id="demo"></p>
    
    <script>
    let x = 123;
    
    document.getElementById("demo").innerHTML = 
    x.valueOf() + "<br>" +
    (123).valueOf() + "<br>" +
    (100 + 23).valueOf();
    </script>
    Note :- In JavaScript, a number can be a primitive value (typeof = number) or an object (typeof = object).

    The valueOf() method is used internally in JavaScript to convert Number objects to primitive values.

    There is no reason to use it in your code.

    All JavaScript data types have a valueOf() and a toString() method.

  15. Converting Variables to Numbers :

    Number Method
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = 
    Number(true) + "<br>" +
    Number(false) + "<br>" +
    Number("10") + "<br>" + 
    Number("  10") + "<br>" +
    Number("10  ") + "<br>" +
    Number(" 10  ") + "<br>" +
    Number("10.33") + "<br>" + 
    Number("10,33") + "<br>" +
    Number("10 33") + "<br>" +
    Number("John");
    </script>
    Note :- If the number cannot be converted, NaN (Not a Number) is returned.

    Number Method Used on Dates Number() can also convert a date to a number.
    <p id="demo"></p>
    
    <script>
    let x = new Date("1970-01-01");
    document.getElementById("demo").innerHTML = Number(x); 
    </script>
    Note :- The Date() method returns the number of milliseconds since 1.1.1970.

    The number of milliseconds between 1970-01-02 and 1970-01-01 is 86400000:
    <p id="demo"></p>
    
    <script>
    let x = new Date("1970-01-02");
    document.getElementById("demo").innerHTML = Number(x); 
    </script>

  16. Date Objects :
    <p id="demo"></p>
    
    <script>
    const d = new Date("2022-03-25");
    document.getElementById("demo").innerHTML = d;
    </script>
    Note :- Date objects are static. The "clock" is not "running".

    The computer clock is ticking, date objects are not.

  17. Math Object : The JavaScript Math object allows you to perform mathematical tasks on numbers.
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = Math.PI;
    </script>
    Note :- Unlike other objects, the Math object has no constructor.

    The Math object is static.

    All methods and properties can be used without creating a Math object first.

    Math Properties (Constants) : The syntax for any Math property is : Math.property.
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = 
    "<p><b>Math.E:</b> " + Math.E + "</p>" +
    "<p><b>Math.PI:</b> " + Math.PI + "</p>" +
    "<p><b>Math.SQRT2:</b> " + Math.SQRT2 + "</p>" +
    "<p><b>Math.SQRT1_2:</b> " + Math.SQRT1_2 + "</p>" +
    "<p><b>Math.LN2:</b> " + Math.LN2 + "</p>" +
    "<p><b>Math.LN10:</b> " + Math.LN10 + "</p>" +
    "<p><b>Math.LOG2E:</b> " + Math.LOG2E + "</p>" +
    "<p><b>Math.Log10E:</b> " + Math.LOG10E + "</p>";
    </script>

    Math Methods : The syntax for Math any methods is : Math.method(number).

    Math.round() Math.round(x) returns the nearest integer:
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = Math.round(4.6);
    </script>

    Math.ceil() Math.ceil(x) returns the value of x rounded up to its nearest integer:
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = Math.ceil(4.7);
    </script>

    Math.floor() Math.floor(x) returns the value of x rounded down to its nearest integer:
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = Math.floor(4.7);
    </script>

    Math.trunc() Math.trunc(x) returns the integer part of x:
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = Math.trunc(4.7);
    </script>

    Math.random() Math.random() returns a random number between 0 (inclusive), and 1 (exclusive):
    <p>Code to create 4 digit random opt number</p>
    
    <button onclick="document.getElementById('demo').innerHTML = getRndInteger(1000,9999)">Click Me</button>
    
    <p id="demo"></p>
    
    <script>
    function getRndInteger(min, max) {
    return Math.floor(Math.random() * (max - min)) + min;
    }
    </script>

    Note :- Math.random() always returns a number lower than 1.

    Math.random() used with Math.floor() can be used to return random integers.

    You can also go through with the below methods :
    Math.sign()
    Math.pow()
    Math.sqrt()
    Math.abs() , etc...

  18. HTML DOM Document :

    getElementById()
    The getElementById() method returns an element with a specified value.

    The getElementById() method returns null if the element does not exist.

    The getElementById() method is one of the most common methods in the HTML DOM. It is used almost every time you want to read or edit an HTML element.
    document.getElementById(elementID)
    Note :- Any id should be unique, but:

    If two or more elements with the same id exist, getElementById() returns the first.

    getElementsByClassName() The getElementsByClassName() method returns a collection of elements with a specified class name(s).

    The getElementsByClassName() method returns an HTMLCollection.

    The getElementsByClassName() property is read-only.
    document.getElementsByClassName(classname)

    getElementsByName() The getElementsByName() method returns a collection of elements with a specified
    The getElementsByName() method returns a live
    getElementsByName()

    getElementsByTagName() The getElementsByTagName() method returns a collection of all elements with a specified tag name.

    The getElementsByTagName() method returns an HTMLCollection.

    The getElementsByTagName() property is read-only.
    document.getElementsByTagName(tagname)
    Note :- getElementsByTagName("*") returns all elements in the document.

    querySelector The querySelector() method returns the first element that matches a CSS selector.

    To return all matches (not only the first), use the querySelectorAll() instead.

    Both querySelector() and querySelectorAll() throw a SYNTAX_ERR exception if the selector(s) is invalid
    document.querySelector(CSS selectors)

    querySelectorAll() The querySelectorAll() method returns all elements that matches a CSS selector(s).

    The querySelectorAll() method returns a NodeList.

    The querySelectorAll() method throws a SYNTAX_ERR exception if the selector(s) is invalid
    document.querySelectorAll(CSS selectors)

  19. HTML DOM MouseEvent : HTML DOM allows JavaScript to react to HTML events:

    Reacting to Events A JavaScript can be executed when an event occurs, like when a user clicks on an HTML element.

    To execute code when a user clicks on an element, add JavaScript code to an HTML event attribute:

    Examples of HTML events:
    When a user clicks the mouse
    When a web page has loaded
    When an image has been loaded
    When the mouse moves over an element
    When an input field is changed
    When an HTML form is submitted
    When a user strokes a key

    The content of the (h2) element is changed when a user clicks on it:
    <h2 onclick="this.innerHTML='Ooops!'">Click on this text!</h2>

    A function is called from the event handler:
    <h2 onclick="changeText(this)">Click on this text!</h2>
    
    <script>
    function changeText(id) {
    id.innerHTML = "Ooops!";
    }
    </script>

    Assign an onclick event to a button element:
    <button onclick="displayDate()">The time is?</button>
    
    <script>
    function displayDate() {
    document.getElementById("demo").innerHTML = Date();
    }
    </script>
    
    <p id="demo"></p>

    oncontextmenu Event The oncontextmenu event occurs when the user right-clicks an HTML element to open the context menu.
    <div id="div01" style="border:1px solid black; padding:10px">
    <p>Right-click in this box to see the hidden content!</p>
    </div>
    
    <div id="myDiv" style="visibility:hidden">
    <p>This is Kaushal</p>
    <p>from SpecBits</p>
    </div>
    
    <script>
    // Assign an "contextmenu" event to div01:
    document.getElementById("div01").addEventListener("contextmenu", myFunction);
    
    // Prevent default context menu:
    const div = document.getElementById("div01");
    div.addEventListener("contextmenu", (e) => {e.preventDefault()});
    
    // Show hidden content:
    function myFunction() {
    const div = document.getElementById("myDiv");
    div.style.visibility = "visible";
    }
    </script>

    ondblclick Event The ondblclick event occurs when the user double-clicks on an HTML element.
    <p id="demo" ondblclick="myFunction()">Double-click me.</p>
    
    <script>
    function myFunction() {
    document.getElementById("demo").innerHTML = "I was double-clicked!";
    }
    </script>

    onmouseenter Event The onmouseenter event occurs when the mouse pointer enters an element.

    The onmouseenter event is often used together with the onmouseleave event, which occurs when the mouse pointer leaves an element.

    The onmouseenter event is similar to the onmouseover event. The difference is that the onmouseenter event does not bubble (does not propagate up the document hierarchy).
    <p>Assign an "onmouseenter" and "onmouseleave" event to a h1 element.</p>
    
    <h1 id="demo">Mouse over me</h1>
    
    <script>
    document.getElementById("demo").onmouseenter = function() {mouseEnter()};
    document.getElementById("demo").onmouseleave = function() {mouseLeave()};
    
    function mouseEnter() {
    document.getElementById("demo").style.color = "red";
    }
    
    function mouseLeave() {
    document.getElementById("demo").style.color = "black";
    }
    </script>

    onmouseleave Event The onmouseleave event occurs when the mouse pointer leaves an element.

    The onmouseleave event is often used together with the onmouseenter event, which occurs when the mouse pointer enters an element.

    The onmouseleave event is similar to the onmouseout event. The difference is that the onmouseleave event does not bubble (does not propagate up the document hierarchy).

    onmousemove Event The onmousemove event occurs when the pointer moves over an element.
    <div onmousemove="myMoveFunction()">
    <p>onmousemove</p>
    <p id="demo1">Mouse over me!</p>
    </div>      
    
    <script>
    let x = 0;
    
    function myMoveFunction() {
    document.getElementById("demo1").innerHTML = x+=1;
    }
    </script>

    The difference between the onmousemove, onmouseenter and mouseover events:
    <div onmousemove="myMoveFunction()">
    <p>onmousemove</p>
    <p id="demo1">Mouse over me!</p>
    </div>
    
    <div onmouseenter="myEnterFunction()">
    <p>onmouseenter</p>
    <p id="demo2">Mouse over me!</p>
    </div>
    
    <div onmouseover="myOverFunction()">
    <p>onmouseover</p>
    <p id="demo3">Mouse over me!</p>
    </div>
    
    <p>The onmousemove event occurs every time the mouse pointer is moved over an element.</p>
    <p>The mouseenter event only occurs when the mouse pointer enters an element. </p>
    <p>The onmouseover event occurs when the mouse pointer enters an div element.</p>
    
    
    <script>
    let x = 0;
    let y = 0;
    let z = 0;
    
    function myMoveFunction() {
    document.getElementById("demo1").innerHTML = z+=1;
    }
    
    function myEnterFunction() {
    document.getElementById("demo2").innerHTML = x+=1;
    }
    
    function myOverFunction() {
    document.getElementById("demo3").innerHTML = y+=1;
    }
    </script>

    The onmouseover and onmouseout Events : The onmouseover and onmouseout events can be used to trigger a function when the user mouses over, or out of, an HTML element:
    <div onmouseover="mOver(this)" onmouseout="mOut(this)" 
    style="background-color:#D94A38;width:120px;height:150px;padding:30px;">
    Mouse Over Me</div>
    
    <script>
    function mOver(obj) {
    obj.innerHTML = "Thank You"
    }
    
    function mOut(obj) {
    obj.innerHTML = "Mouse Over Me"
    }
    </script>

    The onmousedown, onmouseup and onclick Events : The onmousedown, onmouseup, and onclick events are all parts of a mouse-click. First when a mouse-button is clicked, the onmousedown event is triggered, then, when the mouse-button is released, the onmouseup event is triggered, finally, when the mouse-click is completed, the onclick event is triggered.
    <div onmousedown="mDown(this)" onmouseup="mUp(this)"
    style="background-color:#D94A38;width:100px;height:120px;padding:40px;">
    Click Me</div>
    
    <script>
    function mDown(obj) {
    obj.style.backgroundColor = "#1ec5e5";
    obj.innerHTML = "Release Me";
    }
    
    function mUp(obj) {
    obj.style.backgroundColor="#D94A38";
    obj.innerHTML="Thank You";
    }
    </script>

  20. HTML DOM KeyboardEvent : The KeyboardEvent Object handles events that occur when a user presses a key on the keyboard.

    onkeypress Event The onkeypress event occurs when the user presses a key on the keyboard.
    <p>Press a key in the input field:</p>
    
    <input type="text" id="demo">
    
    <script>
    document.getElementById("demo").onkeypress = function() {myFunction()};
    
    function myFunction() {
    document.getElementById("demo").style.backgroundColor = "red";
    }
    </script>
    Note :-The onkeypress event is deprecated.

    It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.

    To detect if the user presses a key, always use the onkeydown event. It works for all keys.

    onkeydown Event The onkeydown event occurs when the user presses a key on the keyboard.
    <p>Press a key in the input field:</p>
    
    <input type="text" onkeydown="myFunction(this)">
    
    <script>
    function myFunction(element) {
    element.style.backgroundColor = "red";
    }
    </script>
    Note :-The onkeypress event is deprecated.

    It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.

    To detect if the user presses a key, always use the onkeydown event. It works for all keys.

    onkeyup Event The onkeyup event occurs when the user releases a key on the keyboard.
    <p>The function transforms the input field to upper case:</p>
    
    Enter your name: <input type="text" id="fname">
    
    <script>
    document.getElementById("fname").addEventListener("keyup", myFunction);
    
    function myFunction() {
    let x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
    }
    </script>
    Note :-The onkeypress event is deprecated.

    It is not fired for all keys (like ALT, CTRL, SHIFT, ESC) in all browsers.

    To detect if the user presses a key, always use the onkeydown event. It works for all keys.

    Using "onkeydown" together with the "onkeyup" event:
    <input type="text" id="demo" onkeydown="keydownFunction()" onkeyup="keyupFunction()">
    
    <script>
    function keydownFunction() {
    document.getElementById("demo").style.backgroundColor = "red";
    }
    
    function keyupFunction() {
    document.getElementById("demo").style.backgroundColor = "green";
    }
    </script>

  21. Form Events

    HTML onsubmit Event Attribute : The onsubmit attribute fires when a form is submitted.
    <form onsubmit="script">

    Example
    <p>When you submit the form, a function is triggered which alerts some text.</p>
    
    <form onsubmit="myFunction()">
    Enter name: <input type="text" name="fname">
    <input type="submit" value="Submit">
    </form>
    
    <script>
    function myFunction() {
    alert("The form was submitted");
    }
    </script>

    HTML onchange Event Attribute : The onchange attribute fires the moment when the value of the element is changed.
    <form onsubmit="script">

    Example
    Enter your name: <input type="text" id="fname" onchange="upperCase()">
    <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
    
    <script>
    function upperCase() {
    const x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
    }
    </script>

    HTML onfocus Event Attribute : The onfocus attribute fires the moment that the element gets focus.

    Onfocus is most often used with (input), (select), and (a).

    Tip: The onfocus attribute is the opposite of the onblur attribute.
    <element onfocus="script">

    Example
    Enter your name: <input type="text" id="myInput" onfocus="focusFunction()" onblur="blurFunction()">
    
    <script>
    // Focus = Changes the background color of input to yellow
    function focusFunction() {
    document.getElementById("myInput").style.background = "yellow";
    }
    
    // No focus = Changes the background color of input to red
    function blurFunction() {
    document.getElementById("myInput").style.background = "red";
    }
    </script>

    HTML onblur Event Attribute : The onblur attribute fires the moment that the element loses focus.

    Onblur is most often used with form validation code (e.g. when the user leaves a form field).

    Tip: The onblur attribute is the opposite of the onfocus attribute.
    <element onblur="script">

    Example
    Enter your name: <input type="text" name="fname" id="fname" onblur="myFunction()">
    
    <p>When you leave the input field, a function is triggered which transforms the input text to upper case.</p>
    
    <script>
    function myFunction() {
    let x = document.getElementById("fname");
    x.value = x.value.toUpperCase();
    }
    </script>


  22. JavaScript Popup Boxes : JavaScript has three kind of popup boxes: Alert box, Confirm box, and Prompt box.

    Alert box An alert box is often used if you want to make sure information comes through to the user.

    When an alert box pops up, the user will have to click "OK" to proceed.
    window.alert("sometext");
    Example
    <button onclick="myFunction()">Try it</button>
    
    <script>
    function myFunction() {
    alert("I am an alert box!");
    }
    </script>
    Note :- The window.alert() method can be written without the window prefix.

    Confirm Box A confirm box is often used if you want the user to verify or accept something.

    When a confirm box pops up, the user will have to click either "OK" or "Cancel" to proceed.

    If the user clicks "OK", the box returns true. If the user clicks "Cancel", the box returns false.
    window.confirm("sometext");
    Example
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    function myFunction() {
    var txt;
    if (confirm("Press a button!")) {
    txt = "You pressed OK!";
    } else {
    txt = "You pressed Cancel!";
    }
    document.getElementById("demo").innerHTML = txt;
    }
    </script>
    Note :- The window.alert() method can be written without the window prefix.

    Prompt Box A prompt box is often used if you want the user to input a value before entering a page.

    When a prompt box pops up, the user will have to click either "OK" or "Cancel" to proceed after entering an input value.

    If the user clicks "OK" the box returns the input value. If the user clicks "Cancel" the box returns null.
    window.prompt("sometext","defaultText");
    Example
    <button onclick="myFunction()">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    function myFunction() {
    let text;
    let person = prompt("Please enter your name:", "Harry Potter");
    if (person == null || person == "") {
    text = "User cancelled the prompt.";
    } else {
    text = "Hello " + person + "! How are you today?";
    }
    document.getElementById("demo").innerHTML = text;
    }
    </script>
    Note :- The window.alert() method can be written without the window prefix.

    Line Breaks To display line breaks inside a popup box, use a back-slash followed by the character n.
    alert("Hello\nHow are you?");

  23. JavaScript HTML DOM EventListener :

    The addEventListener() method The addEventListener() method attaches an event handler to the specified element.

    The addEventListener() method attaches an event handler to an element without overwriting existing event handlers.

    You can add many event handlers to one element.

    You can add many event handlers of the same type to one element, i.e two "click" events.

    You can add event listeners to any DOM object not only HTML elements. i.e the window object.

    The addEventListener() method makes it easier to control how the event reacts to bubbling.

    When using the addEventListener() method, the JavaScript is separated from the HTML markup, for better readability and allows you to add event listeners even when you do not control the HTML markup.

    You can easily remove an event listener by using the removeEventListener() method.

    Syntax
    element.addEventListener(event, function, useCapture);
    The first parameter is the type of the event (like "click" or "mousedown" or any other HTML DOM Event.)

    The second parameter is the function we want to call when the event occurs.

    The third parameter is a boolean value specifying whether to use event bubbling or event capturing. This parameter is optional.

    Note that you don't use the "on" prefix for the event; use "click" instead of "onclick".

    Add an Event Handler to an Element
    <button id="myBtn">Try it</button>
    
    <script>
    document.getElementById("myBtn").addEventListener("click", function() {
    alert("Hello Kaushal");
    });
    </script>
    <button id="myBtn">Try it</button>
    
    <script>
    document.getElementById("myBtn").addEventListener("click", myFunction);
    
    function myFunction() {
    alert ("Hello Kaushal , Welcome to Specbits");
    }
    </script>

    Passing Parameters When passing parameter values, use an "anonymous function" that calls the specified function with the parameters:
    <p>Click the button to perform a calculation.</p>
    <button id="myBtn">Try it</button>
    
    <p id="demo"></p>
    
    <script>
    let p1 = 5;
    let p2 = 7;
    document.getElementById("myBtn").addEventListener("click", function() {
    myFunction(p1, p2);
    });
    
    function myFunction(a, b) {
    document.getElementById("demo").innerHTML = a * b;
    }
    </script>

    The removeEventListener() method The removeEventListener() method removes event handlers that have been attached with the addEventListener() method:
    <style>
    #myDIV {
    background-color: coral;
    border: 1px solid;
    padding: 50px;
    color: white;
    font-size: 20px;
    }
    </style>
    <div id="myDIV">
    <p>This div element has an onmousemove event handler that displays a random number every time you move your mouse inside this orange field.</p>
    <p>Click the button to remove the div's event handler.</p>
    <button onclick="removeHandler()" id="myBtn">Remove</button>
    </div>
    
    <p id="demo"></p>
    
    <script>
    document.getElementById("myDIV").addEventListener("mousemove", myFunction);
    
    function myFunction() {
    document.getElementById("demo").innerHTML = Math.random();
    }
    
    function removeHandler() {
    document.getElementById("myDIV").removeEventListener("mousemove", myFunction);
    }
    </script>

  24. Window Event Attributes :

    HTML onload Event Attribute The onload attribute fires when an object has been loaded.

    onload is most often used within the (body) element to execute a script once a web page has completely loaded all content (including images, script files, CSS files, etc.). However, it can be used on other elements as well.

    The onload attribute can be used to check the visitor's browser type and browser version, and load the proper version of the web page based on the information.

    The onload attribute can also be used to deal with cookies.
    <element onload="script">

    Example
    <body onload="checkCookies()">
    
    <p id="demo"></p>
    
    <script>
    function checkCookies() {
    let text = "";
    if (navigator.cookieEnabled == true) {
        text = "Cookies are enabled.";
    } else {
        text = "Cookies are not enabled.";
    }
    document.getElementById("demo").innerHTML = text;
    }
    </script>
    
    </body>

    HTML onunload Event Attribute The onunload attribute fires once a page has unloaded (or the browser window has been closed).

    onunload occurs when the user navigates away from the page (by clicking on a link, submitting a form, closing the browser window, etc.)

    Note: If you reload a page, you will also trigger the onunload event (and the onload event).
    <element onunload="script">

    HTML onresize Event Attribute The onresize attribute fires when the browser window is resized.
    <element onresize="script">


  25. JavaScript Window Location : The window.location object can be used to get the current page address (URL) and to redirect the browser to a new page.

    Window Location Href The window.location.href property returns the URL of the current page.
    <p id="demo"></p>
    
    <script>
    document.getElementById("demo").innerHTML = 
    "The full URL of this page is:<br>" + window.location.href;
    </script>

    Window Location Assign The window.location.assign() method loads a new document.
    <input type="button" value="Load new document" onclick="newDoc()">
    
    <script>
    function newDoc() {
    window.location.assign("https://developersarmy.com")
    }
    </script>
    Note :- Go through with the given below window object.

    window.location.hostname returns the domain name of the web host
    window.location.pathname returns the path and filename of the current page
    window.location.protocol returns the web protocol used (http: or https:)

  26. JavaScript Window History : The window.history object contains the browsers history.

    Window History The window.history object can be written without the window prefix.

    To protect the privacy of the users, there are limitations to how JavaScript can access this object.

    Some methods:
    history.back() - same as clicking back in the browser
    history.forward() - same as clicking forward in the browser

  27. JavaScript Timing Events :
    <p>A script on this page starts this clock:</p>
    
    <p id="demo"></p>
    
    <button onclick="clearInterval(myVar)">Stop time</button>
    
    <script>
    let myVar = setInterval(myTimer ,1000);
    function myTimer() {
    const d = new Date();
    document.getElementById("demo").innerHTML = d.toLocaleTimeString();
    }
    </script>