Download as docx, pdf, or txt
Download as docx, pdf, or txt
You are on page 1of 20

JavaScript

JavaScript can capture various user actions on a web page in the form of different Javascript
events. JavaScript can change the existing HTML of a web page after it is being loaded by
the browser. JavaScript can be used to create highly interactive web pages.
The web browser makes a separate HTTP request for the JavaScript file. The web server
simply sends the file back to the browser as response, without even bothering to know what
it contains. Once the response comes back, the browser executes the JavaScript file.
JavaScript is a client side scripting language that supports object orientation. The file
extension of the JavaScript files should be .js. <script> tag is used to add JavaScript to a
web page.

Variable:
Let (new): let abc;
abc = “hello”; || let abc = “hello”;
Var(old) : var abc = “hello”;
JavaScript

Strict : restrict old variable type and become strict.


"use strict";
abc = "hello"; //throw error due to strict
var a = "hey";
let ab = "hii";
document.write(abc);
document.write(ab);
document.write(a);

Const : it is used to declare a constant variable whose value cannot


be changed.
JavaScript

Operators:
Extra : arithmetic operator : exponential operator ( ** )
Assignment operator : exponential equal to ( **= )
Typeof : it tells us the operand type.
JavaScript
In JavaScript, you can initialise a variable using let, const, or var. We do not need to specify
the datatype while defining a variable.
Variables are containers that are used to store different types of data or information.
Variables are declared using the let or the var keyword. If no keyword is used while declaring
variables, the variable becomes a global variable.
variable name can contain alpha-numeric characters, the underscore, and the dollar but not
any other special characters. A variable name cannot start with a number. It must start with
either an alphabet, the underscore or the dollar. Variable names are case sensitive.
Meaning, abc and Abc are two different variables.

Conditional statement :
1. If
2. Else
3. If-else if-else
4. Switch
switch(variable){
case “1”:
statement;
break;
case”2”:
statement;
break;
.
.
.
Default:
Statement;
Break;}
Loops:
1. while
while(condition){}
2. do-while
do{
JavaScript
}while(condition);
3. for
for(initialization ; condition ; iteration){
statement;
}

4. for-of loop :
for(let element of array){statement}
5. for-in loop :
for(let name on object){statement} // key value pair
6. foreach

The while loop executes a block of code if and as long as a specific condition is
true.

The do-while loop executes the code block inside the loop at least once, even if the condition
fails for the very first time.
The for-of loop is used to iterate through arrays. The loop runs as many times as the number
of elements in the array. In each iteration it picks up one element of the array and assigns it
to a variable for us to use.
The for-in loop works exclusively on JavaScripts objects. The loop would iterate through all
the key-value pairs in an object. In each iteration it picks up one key and assigns it to a
variable for us to use.
JavaScript
The forEach is not a loop, it is a function. The forEach function is used to iterate through
arrays, not objects. The forEach is not a loop, it is a function. The forEach function is used to
iterate through arrays, not objects.

Function :

Function call:
JavaScript

Output: 42,4,6,8,108,4,6,8,10
JavaScript

Anonymous function : This function has no name


JavaScript
JavaScript
Arrow function : it is an alternate way to define a function.

 A function is a block of code which may or may not have a name. A function has two parts:
a function definition and a function call. A function is created when the same piece of code
might be used at multiple places. A function can return only one value.
Anonymous functions are stored in variables. An anonymous function can be called /
invoked using the variable name. The syntax for definition for an anonymous function ends
with a semicolon. The function keyword is not used in the arrow function notation.

Object : it is a data type and a collection of variables.


JavaScript
Dot(.) operator : it is used the property or method of an object and
helps to assign a new value to an existing property.
Sqauare [] brackets : it is used to access the properties of an object
but not the method.

let dog = {
    breed: "gold",
    height: "4ft",
    age : 2,
JavaScript
    display: function(){
        document.write(this.breed+this.height+this.age);
    }
};
dog.weight = 223;
document.write(dog.breed);
document.write(dog.height);
document.write(dog.age);
document.write(dog.weight);
document.write(dog['breed']);
document.write(dog['height']);
document.write(dog['age']);
document.write(dog['weight']);
dog.display();

new Object() : to create a object.


let dog = new Object();

dog.breed= "gold";
dog.height= "height";
dog.age= 2;
dog.display = function() { document.write(this.breed+this.height+this.age);  
};
document.write(dog.breed);
document.write(dog.height);
document.write(dog.age);
dog.display();
Function constructor: it is a normal function used to create an object.
function car(make,model,year){
    this.make = make;
    this.model = model;
    this.year = year;
    this.display = function() {
        document.write(this.make+this.model+this.year);
    };
}

let car1 = new car("hyndai","i2o",2014);


let car2 = new car("honda","city",2005);
let car3 = new car("tata","nano",2012);

car1.display();
car2.display();
car3.display();
JavaScript
object using class:
class car{
    constructor(make,model,year){
        this.make = make;
    this.model = model;
    this.year = year;
    }
    display () {
        document.write(this.make+this.model+this.year);
    };
};
let car1 = new car("hyndai","i2o",2014);
let car2 = new car("honda","city",2005);
let car3 = new car("tata","nano",2012);

for(let prop in car1){


    document.write(prop+":"+car1[prop]+"<br>")
}

for-in loop : it is exclusively used for objects and it iterates through


all the properties in an object.
An object is a collection of variables. The variables in an object can store values of any type.
The variables in an object, since they are attached to an object, are known as properties.
Properties of an object can be accessed using both the dot operator and square brackets.
The dot operator is used to access properties and methods of an object.The dot operator is
used to define a completely new property of an object. The dot operator is used to edit an
existing property of an object.

Arrays:
  let mod = ["html","css","bootstrap","dbms"];
  for(let i of mod){
      document.write(i+" ");
  }
  mod[2]  = "css";
  mod[4] = "php";
  mod.push("php");
  for(let i of mod){
    document.write(i+" ");
}

Arrays as object and Arrays method: push() and pop()


JavaScript
let modu = new Array("html","css","bootstrap","dbms"); //array as object
for(let i of modu){
    document.write(i+" ");
}
modu.push("php");
for(let i of modu){
    document.write(i+" ");
}

foreach() : it is used as a loop but is not a loop ,it is a


function/method used to iterate through arrays.
const arr = [2,4,6,8,10];
let print = function(element){ //anonymous function
    document.write(element+" ");
};
arr.forEach(print);

arr.forEach(function(element){
    document.write(element+" ");
});

arr.forEach(element => document.write(element+" ")); //arrow function

map() : it is specific to array objects.it runs on an array and creates a


new array.
let numbers = [1,2,3,4,5];
let squares = numbers.map(x => x*x);

squares.forEach(function(element){
    document.write(element+" ");
});

filter() : it is used to create a filter on the elements of an array based


on the condition provided by the function.it creates a new array and
assigns the returned values by the filter() to this array.
let numbers = [1,2,3,4,5];
let even = numbers.filter( x =>x%2==0);
JavaScript
even.forEach(function(element){
    document.write(element+" ");
});

Rest parameter : it allows us to collect an indefinite number of


arguments passed to a function in the form of an array.
function sum(...arr){
    let ans =0;
    arr.forEach(function(ele){
        ans+=ele;
    });
    return ans;
}

let s = sum(1,3,5,7);
document.write(s+" ");
s = sum(2,4,6,8);
document.write(s+" ");

function sum(a, b, ...arr){


    // let ans =0;       // 12 14
    let ans  = a+b;     // 16 20
    arr.forEach(function(ele){
        ans+=ele;
    });
    return ans;
}

let s = sum(1,3,5,7);
document.write(s+" ");
s = sum(2,4,6,8);
document.write(s+" ");

spread operator : it spreads or expand a variable into more than one.


also, it spreads an array into its elements. It is denoted by three
dots(…) before a variable name.
let odd =[1,3,5,7,9];
let even =[2,4,6,8,10];

let num = [...odd, ...even];


JavaScript
num.forEach(function(elem){
    document.write(elem+" ");
});
// 1 3 5 7 9 2 4 6 8 10
An array is a special type of variable that can store multiple values, provided they are
of the same type. An array is used to store a large set of data. An array can also be
defined as an object.
The filter() function creates a new array with the filtered elements based on a
condition provided by a function.
The map() function creates a new array populated with the results of calling a
provided function on every element in the calling array.
A rest parameter allows us to collect an indefinite number of arguments passed to a
function. A rest parameter collects data in the form of an array. A rest parameter is
represented by 3 dots before a variable name.
A spread operator allows an array to be expanded in places where multiple elements
are expected. A spread operator, exactly like the rest parameter, is represented by 3
dots before a variable name.

Strings : A string is any text or a sequence of characters. They are enclosed within quotes
(single quotes or double quotes). They can be either primitive strings or string objects.

Concatenated(+): In JavaScript, plus operator is used to concatenate two strings.


Template literals : it is a string enclosed by (`).it allows us toprint a
variable within a string. We can put any variable inside the dollar symbol and curly
braces ${ } in string literals to get its value.

let name = "joe";


let s = `hello ${name}!`;
document.write(s);

string as object:
let str = new String("hello");
document.write(str.length);

length property : it help us to identify the length of a string.

 indexOf()
JavaScript
The indexOf() method returns the index of (the position of)
the first occurrence of a specified text in a string:
let str = "Please locate where 'locate' occurs!";
str.indexOf("locate");
output : 7

 slice()

slice() extracts a part of a string and returns the extracted part in a


new string

let str = "Apple, Banana, Kiwi";


let part = str.slice(7, 13);

output: banana

substring() is similar to slice().

The difference is that substring() cannot accept negative indexes.

 replace()

he replace() method replaces a specified value with another value in


a string:

let text = "Please visit Microsoft!";


let newText = text.replace("Microsoft", "W3Schools");

output: Please visit Microsoft!

 startsWith()

The startsWith() method returns true if a string begins with a


specified value, otherwise false:

let text = "Hello world, welcome to the universe.";

text.startsWith("Hello");
JavaScript
output:true

 endsWith()

The endsWith() method returns true if a string ends with a specified


value, otherwise false:

var text = "John Doe";


text.endsWith("Doe");
output:true

 include()

The includes() method returns true if a string contains a specified


string.
Otherwise it returns false.
The includes() method is case sensitive.
let text = "Hello world, welcome to the universe.";
let result = text.includes("world", 12);
output:false

DOM(document object model): it is a programming interface. It helps


to access the html elements of web page in the form of javascript
objects.

Method:
 getElementById
The getElementById() method returns only the first HTML element that
matches the given id.

let tag = document.getElementsById("abc");


 getElementByClassName
let c = document.getElementsByClassName("xyz");
 getElementByTagName
The getElementsByTagName() method fetches all the HTML elements with
the given tag name or element type in the form of an array.
let pa  = document.getElementsByTagName("p");
JavaScript
 querySelectorAll
let els = document.querySelectorAll(".xyz");
it will contains of javascript array of type nodes.

Properties:
 innerHTML : it helps to fetch the content of the element.
The innerHTML property is used to both fetch and set the content of an HTML
element.
let tag = document.getElementById("abc");
alert(tag.innerHTML);
tag.innerHTML = "this is new para";
tag.style.color = "red";
 Event handler: OnClick : it is used to capture user clicks.
Event handlers go by the name onEventName. The event handlers
continue to run forever, till the web page is closed. There is an
alternative way of using event handlers - as attributes to HTML
elements.
let tag = document.getElementById("abc");
tag.onclick = function(){
    tag.innerHTML = "this is new para";
    tag.style.color = "red";
}
Since, JavaScript runs on the browser, JavaScript can capture various user actions on a
web page in the form of different Javascript events, and also, it can make changes to the
existing HTML elements of a web page even after they have been rendered by the browser.

Using the sources tab of inspect element we can debug JavaScript.


We can add a breakpoint in the JavaScript file on the sources tab by clicking on the line
numbers - it will add a colored marker which is a breakpoint. We can add a breakpoint in the
JavaScript file on the sources tab by clicking on the line numbers - it will add a colored
marker which is a breakpoint. A breakpoint pauses the code execution if and when the
execution reaches that line. When the code execution is paused, we have two options,
resume and step over.

The replace() function replaces only the first occurrence of the first parameter with the
second one.
slice(-30) indicates extract last 30 elements from the sequence.
The onclick event executes the defined function when the user clicks the specific element on
which the onclick event handler is set.
JavaScript
No, the browser can never know what all is present on the server, unless the server sends
that information to the browser. The sources tab displays only those files that get loaded on
the browser while fetching the main web page.
Step-over takes the code execution to the very next line, but in the paused state.
The httpRequest.status stores the value of the HTTP response code. When an Ajax request
is successfully completed, the response code is 200.

Ajax(Asynchronous Javascript and XML) :


It is a technique to initiate an http request through javascript
without reloading a web page. If we also want to update the
database or to get some information we need to use ajax.
Ajax is just a way to initiate an HTTP request. Server-side logic is still written in PHP.
XMLHttpRequest is a class or a predefined function constructor in Javascript, using which
we initiate Ajax requests.
The httpRequest.onreadystatechange is supposed to store a function we define that the
browser automatically invokes after the completion of the AJAX request
The first argument to the httpRequest.open() method is the HTTP request method type for
the Ajax request we want to initiate, like the GET or the POST.
The second argument to the httpRequest.open() method is a URL to which we want to make
the Ajax request.

You might also like