DEV Community

Cover image for Getting started with Javascript
Ruthvik Raja M.V
Ruthvik Raja M.V

Posted on

Getting started with Javascript

JS is an event - based programming language.
(APPLICATION TO EXECUTE - VISUAL STUDIO CODE)

In computer programming, event-driven programming is a programming paradigm in which the flow of the program is determined by events such as user actions, sensor outputs, or messages from other programs or threads.

If we use client-side scripting language JavaScript, this can be done without consulting the server

Only language understood by the browser.

Developers choose JavaScript to create dynamic, interactive and scalable web applications. JavaScript helps developers in extending the functionalities of web pages effectively. It helps primarily in reducing the number of request-response cycles and decreasing the network bandwidth. JavaScript helps in reducing the response time.

 <script>
 document.write(hello world)
 </script>
Enter fullscreen mode Exit fullscreen mode

When lines of JavaScript code are written within the HTML file itself, it is called internal scripting.
Javascript code can be written inside a head tag or body tag.
If you want to link the javascript file in a html code then:

<script src=  ></script>
Enter fullscreen mode Exit fullscreen mode

Internal scripting takes less loading time than external scripting.

The identifier that we choose to hold data which does not vary is called Constant.

const type=car;
Enter fullscreen mode Exit fullscreen mode

undefined is a data type in JavaScript that has a single value also termed as undefined.
Any variable that has not been assigned a value during declaration will be automatically assigned with the value undefined.

Ex : var custname (where value is undefined and datatype is also undefined)
Enter fullscreen mode Exit fullscreen mode

Even we can assign it with undefined like

var custname=undefined;
var item=null;
Enter fullscreen mode Exit fullscreen mode

If you are wondering why would we need such a data type, the answer is JavaScript variable intended to be assigned with the object at a later point in the program can be assigned null during the declaration.

===(returns true when the value and the datatype, both are equal)
!==(returns true when value or datatype are in-equal)
typeof(10>20) -> False.
Conditional expression: (age>60) ? senior citizen : normal citizen;
// single line comments,
/* double line comments */ > <!——- ———>
Enter fullscreen mode Exit fullscreen mode

How to use div tag in a html file:

<html> <head>
<style> div#maincontent {
height: 250px;
width: 500px;
border: 1px solid #CEE2FA; text-align: left;
color: #08438E; font-family: calibri; font-size: 20;
padding: 5px;
} </style>
</head>
<body> <center>
<div id=maincontent>
<script>
document.write(Hello world);
</script> </div>
</center> </body>
</html>
Enter fullscreen mode Exit fullscreen mode

User defined functions:

function function_name(parameter 1, parameter 2); { return value; }
function_name(); > calling a function
Enter fullscreen mode Exit fullscreen mode

Nested Functions:
In JavaScript it is perfectly normal to have functions inside functions. The function within another function body, is called as nested function.

The nested function is private to the container function and cannot be invoked from outside the container function.

document.write(<br><br>); > this will provide you gap between the statements.
Enter fullscreen mode Exit fullscreen mode

In-Built Functions:(few are:)

alert(); isNaN();—>this checks if it is number or not

confirm(); parseInt(),parseFloat()—>this will parses the
String and reruns integer and a float number.

prompt(); isNaN(is not a number).

Examples for the above functions:

 <script>
 //1. alert
 alert("Let us proceed");
//2. confirm
var decision = confirm("Shall we proceed?");
if (decision) document.write("You decided to
proceed" + "<br><br>");
  "<br><br>");
else document.write("You decided not to proceed" +
  //3. prompt
 var userInput = prompt("Please enter your name:");
 document.write("Hello dear " + userInput +
 "<br><br>");
 //4. isNaN
 var isNotNumber1 = isNaN(30);
 var isNotNumber2 = isNaN("hello");
 document.write("30 is not a number:" +
 isNotNumber1 + "<br>");
 document.write("hello is not a number:" +
 isNotNumber2 + "<br><br>");
 //5. isFinite
 var isNumber1 = isFinite(30);
 var isNumber2 = isFinite("hello");
 document.write("30 is a number:" + isNumber1 +
 "<br>");
 document.write("hello is a number:" + isNumber2 +
 "<br><br>");
 //6. parseInt
 document.write('parseInt("10"): ' + parseInt("10")
 + "<br>");
 document.write(
 'parseInt("10 20 30"): ' + parseInt("10 20
 30") + "<br>"
 );
 document.write(
 'parseInt("10 years"): ' + parseInt("10
 years") + "<br>"
 );

  10") + "<br><br>"
document.write(
 'parseInt("years 10"): ' + parseInt("years
  );
 //7. parseFloat
document.write(
 'parseFloat("10.34"): ' + parseFloat("10.34")
 + "<br>"
 );
 document.write(
 'parseFloat("10 20 30"): ' + parseFloat("10 20
 30") + "<br>"
 );
 document.write(
 parseFloat("10.50 years") + "<br>"
'parseFloat("10.50 years"): ' +
  );
 document.write(
 'parseFloat("years 10"): ' + parseFloat("years
 10") + "<br><br>"
 );
 //8. eval
 eval("2*3");
 document.write(eval("2*3") + "<br><br>");
 eval(
 "var num1=2;var num2=3;var
 result=num1*num2;document.write(result+'<br><br>')"
 );
 timeout!" + "<br><br>");
//9. setTimeout
 function executeMe1() {
 document.write("Function says hello after
  }

setTimeout(executeMe1, 3000);
interval!" + "<br>");
//10.setInterval
function executeMe2() {
document.write("Function says hello every
}
setInterval(executeMe2, 3000);
</script>
Enter fullscreen mode Exit fullscreen mode

The setTimeout(function_name,”time in milli_sec”);
method calls a function or evaluates an expression
after a specified number of milliseconds.

The only difference is , setTimeout() triggers the expression only once while setInterval() keeps triggering expression regularly after the given interval of time.

Scopes:

Local, global and nested —> scopes available.

As observed, without the use of keyword 'var', local scope changes to the global scope. If any variable is declared inside a function without the use of var then it can be accessed from outside of the function also.

Nested scope:

//variable declaration global

function f1( );
{
     Global variables are accessible and local variables;

     function f2( );
       {
              Global variables, local variables and nested variables are accessible;
        }
}
Enter fullscreen mode Exit fullscreen mode

Scopes - Hoisting:

JavaScript interpreter follows the process called hoisting.
Hoisting means all the variable and function declarations wherever they are present throughout our program, get lifted and declared to the top of the program, in case of global scope, and on top of the function declaration in case of function/local scope.

<script>
    document.write("firstname" + "<br><br>" + first + "<br><br>");
    var first = "ramesh";
</script>

o/p: first name   undefined.

Enter fullscreen mode Exit fullscreen mode

But interpreter says that variable is not defined. This is because hoisting only lifted the variable declaration on the top and not initialisation.

<script>
    var o = "car";

    function fu() {
        var i = "bike";

        l = "bus"
    }
    fu();
    document.write(o + "<br>");
    document.write(i + <br>);           //line 2
    document.write(l + "<br>");
</script>

  O/P :  car  but bus wont be printed because while accessing i It fails and bus wont be printed. If we comment the second then it prints  car and bus.
Enter fullscreen mode Exit fullscreen mode

Events and Event Handling:

When the interaction happens, the event triggers. JavaScript event handlers enable the browser to handle them. JavaScript event handlers invoke the JavaScript code to be executed as a reaction to the event triggered.

Screenshot 2021-05-29 at 12.35.36 AM

Ex : <p onclick = execute_me( ) >  welcome </p>.
 Where <p> is a html tag and execute_me( ) is a javascript tag.
<script src=myscript.js></script>  used to refer external javascript file.

 <a  href='' onclick='calculateDiscount(event);'>Apply</a>

href is useful to get a line under Apply.
The above function code is::
function calculateDiscount(event) {
                    event.preventDefault();
                    var discount = 10;
                    const percent = 100;
                    for (index = 1; index <= seats; index++) {
                        discountedCost =
                            costPerTicket - (discount / percent) * costPerTicket;
                        cost = cost + discountedCost;
                        discount = discount + 10;
                    }
                    alert(
                            "Amount payable after discount is: Rs." + cost
                        )
Enter fullscreen mode Exit fullscreen mode

Example:

Execute the below code with calculateDiscount(event) and with calculateDiscount() to view the changes.

<html>

<head>
    <style>
        div#maincontent {
            height: 100px;
            width: 500px;
            border: 1px solid #CEE2FA;
            text-align: left;
            color: #08438E;
            font-family: calibri;
            font-size: 20;
            padding: 5px;
        }

        div#heading {
            text-decoration: bold;
            text-align: center;
            margin-top: 80px;
            width: 500px;
            border: 1px solid #CEE2FA;
            text-align: center;
            color: #08438E;
            background-color: #CEE2FA;
            font-family: calibri;
            font-size: 20;
            padding: 5px;
        }

        h2 {
            padding: 0;
            margin: 0;
        }
    </style>
</head>

<body>
    <center>
        <div id="heading">
            <h2>Booking Summary</h2>
        </div>
        <div id="maincontent">
            <script>
                var seats = 4;
                var costPerTicket = 320;
                var cost = 0;
                calculateCost(seats);

                function calculateCost(tickets) {
                    var discountedCost;
                    if (tickets > 2 && tickets <= 6) {
                        document.write(
                            "Cost per ticket is: Rs." + costPerTicket + "<br>"
                        ); //Requirement 4: Calling function to calculate discounted amount, when user clicks on //the hyperlink
                        document.write(
                            "Total cost: Rs." + tickets * costPerTicket + "</b><br>"
                        );
                        document.write(
                            "<br> Congratulations! " +
                            tickets +
                            " seats are eligible for discount. <a  href='' onclick='calculateDiscount(event);'>Apply</a><br><br>"
                        );
                    } else if (tickets > 6) {
                        document.write(
                            "<br>Oops!You cannot book more than 6 tickets!!<br>"
                        );
                    } else {
                        document.write(
                            "Cost per ticket is: Rs." + costPerTicket + "<br>"
                        );
                        cost = tickets * costPerTicket;
                        document.write(
                            "<br><br>" + "Total cost: Rs." + cost + "</b><br>"
                        );
                    }
                }

                function calculateDiscount(event) {
                    event.preventDefault();
                    var discount = 10;
                    const percent = 100;
                    for (index = 1; index <= seats; index++) {
                        discountedCost =
                            costPerTicket - (discount / percent) * costPerTicket;
                        cost = cost + discountedCost;
                        discount = discount + 10;
                    }
                    alert(
                            "Amount payable after discount is: Rs." + cost
                        )
                        /*document.write('<br>'+'Total seats: '+seats+'<br>');
                                           document.write('<br>'+'Amount payable: Rs.'+cost+'<br>');*/
                }
            </script>
        </div>
    </center>
</body>

</html>
Enter fullscreen mode Exit fullscreen mode

Objects in Javascript:

An object consists of state and behaviour. State of an entity represents properties that can be modelled as key-value pairs. The behaviour of an entity represents the observable effect of an operation performed on it and is modelled using functions.
Example: Car is an object.

State of Car object:
Color=red
Model = VXI
Current gear = 3
Current speed = 45 km / hr
Number of doors = 4
Seating Capacity = 5

The behaviour of Car object:
Accelerate
Change gear
Brake

Objects can be created using object literal notation. Object literal notation is a comma-separated list of name-value pairs wrapped inside curly braces. 

We can use dot or operator to access the value.like obj.key (or)
obj[key].

Example for a style tag:

<style>
        div#maincontent {
            height: 150px;
            width: 500px;
            border: 1px solid #CEE2FA;
            text-align: left;
            color: #08438E;
            font-family: calibri;
            font-size: 20;
            padding: 5px;
        }

        div#heading {
            text-decoration: bold;
            text-align: center;
            margin-top: 80px;
            width: 500px;
            border: 1px solid #CEE2FA;
            text-align: center;
            color: #08438E;
            background-color: #CEE2FA;
            font-family: calibri;
            font-size: 20;
            padding: 5px;
        }

        h2 {
            padding: 0;
            margin: 0;
        }
    </style>
Enter fullscreen mode Exit fullscreen mode

Example to create a car object using object Literation:

Create a Car object using literal notation with following properties:
name, model, color, numberOfGears, currentGear, currentSpeed and following methods:
'accelerate' which will accept 'speedCounter' argument and return current speed after adding speedCounter to it.
'brake': which will accept 'speedCounter' argument and return current speed reduced by speedCounter.

<script>
                var myCar = {
                    name: "Fiat",
                    model: "VXI",
                    color: "red",
                    numberofGears: 5,
                    currentGear: 3,
                    currentSpeed: 45,

                    accelerate: function(speedCounter) {
                        this.currentSpeed = this.currentSpeed + speedCounter;
                        return this.currentSpeed;
                    },

                    brake: function(speedCounter) {
                        this.currentSpeed = this.currentSpeed - speedCounter;
                        return this.currentSpeed;
                    }
                };
</script>
Enter fullscreen mode Exit fullscreen mode

And the methods can be called as follows:


myCar["accelerate"](20);
                document.write(
                    "<br>Current speed after accelerating: " + myCar["currentSpeed"]
                );
Enter fullscreen mode Exit fullscreen mode

For calling the methods we can use either dot or [ ] operators.

Example to create a Button:

<html>

<head>
    <title>Literal Notation for Object Creation</title>
    <style>
        body {
            padding-top: 10px;
        }
    </style>
</head>

<body class="container-fluid">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3>Dating App</h3>
        </div>
        <div class="panel-body">
            <input type="button" class="btn btn-success" onclick="myProfile()" value="View Profile">
            <input type="button" class="btn btn-primary" onclick="person.interest()" value="Check interest">
        </div>
    </div>
</body>

</html>

btn btn-success and btn btn-primary belongs to bootstrap buttons.
Enter fullscreen mode Exit fullscreen mode

Another way to create a button:

<button type="button" class="btn btn-primary >Primary</button>

Enter fullscreen mode Exit fullscreen mode

Built in Javascript Objects:

The built-in JavaScript object 'Date' allows us to work with dates and times displayed as part of the webpage.

var obj1 = new Date( );
document.write(obj1) —— this gives the whole data but by using dot operator we can access the date, month etc.

Like obj1.getMonth( ) - this gives the current month.

var obj1 = new Date(year, month, day, hours, minutes, seconds, milliseconds); 

<input type="datetime-local" >
This will display a form to select date and time.
Enter fullscreen mode Exit fullscreen mode

Strings:(there are various inbuilt string functions available in javascript)—->all are available in Visual Studio Code App.

ex:
var my_string=hello;
my_string.length;

Enter fullscreen mode Exit fullscreen mode

Regular Expressions:

var obj1=new RegExp(pattern,modifiers);

Where modifiers are optional: g , m, i
g- performs global match
m- performs multi-line match
 i - performs case-insensitive match

Example to check whether the input is a valid email??

var email_pattern=new RegExp((?=.*@)(?=.+.com));

var email_string=prompt(please enter the email id);

if(!(email_pattern.test(email_string)))
   alert(email_id is invalid);
else
  alert(email_id is valid);
Enter fullscreen mode Exit fullscreen mode

Example of a Javascript Code:

<form class="form-signin">
                <input type="text" id="username" onkeyup="checkName();" class="form-control" placeholder="Enter username" /><br /><br />
                <input type="password" id="pwd" onkeyup="checkPassword();" class="form-control" placeholder="Enter password" /><br /><br />
                <input type="email" id="mail" onkeyup="checkEmail();" class="form-control" placeholder="Enter email" /><br /><br />
                <input type="number" id="phone" onkeyup="checkPhone();" class="form-control" placeholder="Enter phone number" /><br /><br />
                <button type="submit" onclick="alert('Form submitted successfully!')" class="btn btn-primary">
                    Submit
                    </button>
                <p style="color:red" id="message"></p>
            </form>
Enter fullscreen mode Exit fullscreen mode

The onkeyup event occurs when the user releases a key (on the keyboard).

Arrays:

Array in JavaScript is an object that allows storing of multiple values in a single variable.

var obj1=new Array(1,2,3);
       or              
var sample=[1,2,3];
Enter fullscreen mode Exit fullscreen mode

JavaScript arrays are allowed to contain elements of different types. Such an array is called as dense array
and there are various built in functions like:

obj1.push(2);
obj1.pop( );
obj1.splice(x,y,z); where x is the index of new item, y is the 
         Number of items to be removed starting from the index
         Next to the new item index number(x) and z is the new 
         Item.
obj1.concat(obj2);
forEach:
var myArray = ["Android", "iOS", "Windows"];
myArray.forEach( function( currentItem, index){
console.log("myArray has" + currentItem +"at index" + index);
})

Enter fullscreen mode Exit fullscreen mode

Next object under the category of global objects in JavaScript is Math. It is the JavaScript object that is used to make mathematical calculations on the web.
We can call properties and methods of this object without instantiation of this object because the Math object cannot be instantiated.

Math.PI;
Math.sqrt(5);, Math.random( ); etc there are various inbuilt methods.
Enter fullscreen mode Exit fullscreen mode

Difference between JSON AND JAVASCRIPT code:

For JavaScript objects we do not put the key in quotes and if values are of string data type they can be put in single or double-quotes.
But for JSON object, it is mandatory to put the key inside the double quotes and all the values of type string inside the double-quotes.

Conversion of javascript code to JSON:

var txt = {
        "name": "John",
        "age": 30,
        "city": "New York"
    };
    document.write(JSON.stringify(txt));

From json to javascript we have to use JSON.parse();
var user = JSON.parse(
        '{"name":"Mary","email":"mary123@gmail.com","mobile":1234567890,"password":"mary@123"}'
    );

Enter fullscreen mode Exit fullscreen mode

BOM(Browser Object Model):

The dynamic manipulation of an HTML page on the client-side itself is achieved with the help of built-in browser objects. They allow JavaScript code to programmatically control the browser and are collectively known as Browser Object Model (BOM).

'Window' object is the root object and consists of other objects in a hierarchy, namely, 'history' object, 'navigator' object, 'location' object and 'document' object.

The HTML web page that gets loaded on the browser is represented using the 'document' object of BOM model.
This object considers the web page as a tree which is referred to as Document Object Model (DOM).

To access an element in HTML page we can use following methods on 'document' object from DOM API:

getElementById( );
document.getElementsByTagName(p);
getElementsByClassName(x);
Enter fullscreen mode Exit fullscreen mode

To manipulate the content of HTML page we can use the following properties of 'element' object:

Example:

<div id="div1">
    <h1 id="heading1">welcome to JS</h1>
    <p id="p1">welcome to para</p>
</div>

<script>
    //retrieves current element
    document.getElementById("heading1").innerHTML;

    //sets the new content
    document.getElementById("heading1").innerHTML = " new heading";
</script>

Enter fullscreen mode Exit fullscreen mode

Attributes in DOM:

Before knowing this see the following HTML Code:
Using The class Attribute

<!DOCTYPE html>
<html>
<head>
<style>
.cities {
  background-color: black;
  color: white;
  margin: 20px;
  padding: 20px;
}
</style>
</head>
<body>

<div class="cities">
  <h2>London</h2>
  <p>London is the capital of England.</p>
</div>

<div class="cities">
  <h2>Paris</h2>
  <p>Paris is the capital of France.</p>
</div>

<div class="cities">
  <h2>Tokyo</h2>
  <p>Tokyo is the capital of Japan.</p>
</div>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Now example for a set Attribute using a JAVASCRIPT Code::

<!DOCTYPE html>
<html>
<head>
<style>
.democlass {
  color: red;
}
</style>
</head>
<body>

<h1>Hello World</h1>
<h1>Hello world 2 </h1>
<h1>hello world 3</h1>

<p>Click the button to add a class attribute with the value of "democlass" to the h1 element.</p>

<button onclick="myFunction()">Try it</button>

<script>
function myFunction() {
  document.getElementsByTagName("h1")[0].setAttribute("class", "democlass"); 
}
</script>

</body>
</html>
Enter fullscreen mode Exit fullscreen mode

To manipulate the style of an HTML element we can use the following property of 'element' object given by DOM API:
Example:

<html>
<body>
    <style>
        div#id1 {
            color: red;
        }
    </style>

    <div id='id1'>
        <h1> HEADING </h1>
    </div>

    <input type=button"  onclick="my_function()">Enter</input>

    <script>
        function my_function() {
            document.getElementById("id1").style.color = 'blue';

        }
    </script>


</body>
</html>
Enter fullscreen mode Exit fullscreen mode

Example that includes all DOM API’s:


<html>

<head>
    <style>
        body {
            padding-top: 10px;
        }
    </style>
</head>

<body class="container-fluid">
    <div class="panel panel-primary">
        <div class="panel-heading">
            <h3>DOM API </h3>
        </div>
        <div class="panel-body">
            <script>
            </script>
            <p id="p1">This para has attribute id and will help us with selection</p>

            <p>This para does not have an attribute id</p>

            <p class="myClass">This para has attribute id and will help us with selection</p>

            <p class="blue">This para has attribute class and will help us with selection</p>
            <div id="div1">
                <h1 id="heading1">Welcome to JavaScript ILP tutorial</h1>
                <p id="para1" style="color:blue">Let us learn DOM API</p>
            </div>

            <hr>
        </div>
    </div>
    <script>
        document.write("Scripting output" + "<br><br>");

        // 1. DOM API method - getElementById
        var para = document.getElementById("p1");

        // 2. DOM API method to change the content of HTML element - innerHTML
        document.write("document.getElementById p1: " + para.innerHTML + "<br><br>");

        //3. DOM API method to access multiple elements with same tag name - getElementsByTagName
        var paras1 = document.getElementsByTagName("p");
        for (i = 0; i < paras1.length; i++) {
            document.write(
                "document.getElementsByTagName p: " + paras1[i].innerHTML + "<br><br>"
            );
        }

        //4. DOM API method to access multiple elements with same class attribute's value - getElementsByClassName
        var paras2 = document.getElementsByClassName("myClass");
        for (i = 0; i < paras2.length; i++) {
            document.write(
                "document.getElementsByClassName myClass: " +
                paras2[i].innerHTML +
                "<br><br>"
            );
        }

        //5. DOM API method to access multiple elements with given CSS selector - querySelectorAll
        var x = document.querySelectorAll("p.blue");
        document.write("x[0].innerHTML: " + x[0].innerHTML + "<br><br>");

        //6. DOM API method to retrieve current content
        document.write(
            "document.getElementById heading1 innerHTML: " +
            document.getElementById("heading1").innerHTML +
            "<br><br>"
        );

        //7. DOM API method to set new content

        document.getElementById("heading1").innerHTML =
            "Heading content generated dynamically";

        document.write(
            "updated document.getElementById heading1 innerHTML: " +
            document.getElementById("heading1").innerHTML +
            "<br><br>"
        );

        //8. DOM API method to retrieve current attributes value

        document.write(
            "document.getElementById div1 attributes[0].value: " +
            document.getElementById("div1").attributes[0].value +
            "<br><br>"
        );

        //9. DOM API method to set or add new attribute

        document.getElementById("div1").setAttribute("class", "div2");

        //10. style change
        document.getElementById("para1").style.color = "red";
    </script>
</body>

</html>

Enter fullscreen mode Exit fullscreen mode

Usage of span tag in HTML:

<p>My mother has <span style="color:blue">blue</span> eyes.</p>
It is used to style a part of a text.
Enter fullscreen mode Exit fullscreen mode

BOM - Window Object:

If we want to navigate to a different URL and bring a new web page, or you want to close the web page or you want to store some data related to the web page. Well, to implement this, we would need an object that represents the entire browser window and allows us to access and manipulate the window properties. BOM model provides us 'window' object.


<script>
    //holds inner height of window's content area
    var height = window.innerHeight;
    document.write(height + "<br><br>");

    //holds inner width of window's content area
    var width = window.innerWidth;
    document.write(width + "<br><br>");

    //holds outer height of window including toolbars and scrollbars
    var outheight = window.outerHeight;
    document.write(outheight + "<br><br>");

    //holds outer width of window including toolbars and scrollbars
    var outwidth = window.outwidth;
    document.write(outwidth + "<br><br>");
</script>
Enter fullscreen mode Exit fullscreen mode

The localStorage and sessionStorage properties allow to save key/value pairs in a web browser.
The localStorage object stores data with no expiration date. The data will not be deleted when the browser is closed, and will be available the next day, week, or year. The localStorage property is read-only.
The sessionStorage object stores data for only one session (the data is deleted when the browser tab is closed).

<script>
    localStorage.setItem("username", "bob");
    document.write(localStorage.getItem("username"));

    sessionStorage.setItem("password", "@123");
    document.write(sessionStorage.getItem("password"));
</script>


Additionally: window.open(http://www.fb.com“);
              window.close();//closes current
                               window.
Enter fullscreen mode Exit fullscreen mode

BOM - History Object:

It provides programmatic navigation to one of the URLs previously visited by the user. Following are the properties or methods that help us do it.
history.length will gives the number of elements in history list.
history.back(); , history.forward();
history.go();—>loads previous url present at the given number from the history list.
Ex: window.history.go(-2) //go two pages back, loads a specific URL from the history list.

BOM - Navigator Object:

It contains information about the client, that is, the browser on which the web page is rendered.

navigator.userAgent();

//used for returning the user-agent header's value sent to the server by the browser. It returns a string representing values such as the name, version, and platform of the browser.

<script>
    //returns name of the client(browser)
    document.write(navigator.appName + "<br><br>");

    //returns platform(OS) and version of client(browser)
    document.write(navigator.appVersion + "<br><br>");

    //returns the name of the user's operating system
    document.write(navigator.platform + "<br><br>");

    document.write(navigator.userAgent);
</script>
Enter fullscreen mode Exit fullscreen mode

BOM - Location Object:

If we want to programmatically refresh the current page or navigate to a new page which object shall we use? — location object is used.

href contains entire url as a string —>location.href;
location.reload(); —> to reload a current html document.
location.assign(); —->loads new html document.

<html>
<body>
    <button onclick="myFunction()">Load new document</button>
    <script>
        function myFunction() {
            location.assign("https://www.w3schools.com");
        }
    </script>
</body>
</html>

local.hostname;, location.port;, location.pathname; 
Enter fullscreen mode Exit fullscreen mode

DOM:

<html>
<head>
</head>

<body>
    <div id="div1">
        <h1 id="h"></h1>
        <p id="p"></p>
    </div>
    <script>
        document.write(document.body.parentNode + "<br>");
        document.write(document.body.childNodes + "<br>");
        document.write(document.getElementById("div1").firstElementChild + "<br>");
        document.write(document.getElementById("div1").lastElementChild + "<br>");
        document.write(document.getElementById("h").nextElementSibling + "<br>");
        document.write(document.getElementById("p").previousElementSibling);
    </script>

</body>
</html>

Example::
<html>
<head>
</head>
<body>
    <div id="div1">
        <h1 id="h"></h1>
        <p id="p"></p>
    </div>
    <script>
        //creates new element
        var next_ele = document.createElement('span');
        document.write(next_ele);

        //creates content at runtime
        var next_text=document.createTextNode('the span element is added');

        //appending the child element
        document.getElementById("div1").appendChild(next_ele);
        document.getElementById("div1").appendChild(next_text);

        //removing an element from DOM tree
        document.getElementById("div1").removeChild(document.getElementById("h"));
    </script>

</body>
</html>

Enter fullscreen mode Exit fullscreen mode

Other Concepts:

Unlike variables declared with var are function-scoped, variables declared with let and const are block-scoped.

function text() {
        if (10 == 10) {
            let flag = "true";
        }
        document.write(flag);
    }
    text();
                            //This throws an error
Enter fullscreen mode Exit fullscreen mode

When you are looping, and looping variables are never used outside the block then we can use let keyword.
const is to be used in place of ‘let’ when the variable value should remain constant and shouldn’t be allowed to change throughout the program.

const keyword can also be used for arrays and other objects.

Example: 
const my_array=[1,2,3];
               my_array=[8,9,10]         // throws an error
             my_array.push(4)            //this does not throws any error.
Enter fullscreen mode Exit fullscreen mode

THE END...
If you want the above stuff as a pdf document, feel free to message me.

Top comments (0)