map method

The map method in JavaScript is an array method used to create a new array by applying a provided function to each element in the original array. It’s particularly useful when you need to transform or process each element and return a new array with the results, leaving the original array unchanged.

Syntax:


const newArray = array.map(function(element, index, array) {
  // Return transformed element here
}, thisArg);

element: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array map was called upon.

thisArg (optional): A value to use as this when executing the callback function.

Characteristics of map

1. Returns a New Array: The map method returns a new array containing the results of applying the provided function to each element of the original array.

2. Original Array Unchanged: The original array remains unchanged after the map operation.

3. Transforms Each Element: The function provided to map transforms each element in the array, and the result of this transformation is stored in the new array.

4. Iterates Over Every Element: The function passed to map is called for every element in the array, even if the element is undefined, null, or an empty slot.

5. Chaining: Since map returns a new array, you can chain other array methods like filter, reduce, etc., on the result.

Example:


const numbers = [1, 2, 3, 4];
const updatedNumbers = numbers.map(num => num * 5);

console.log(updatedNumbers); // Output: [5, 10, 15, 20]
console.log(numbers); // Output: [1, 2, 3, 4] (original array is unchanged)

Extracting Specific Properties:


const users = [
    {name: 'John', age: 39},
    {name: 'Tom', age: 38},
    {name: 'Mathew', age: 35}
];

const names = users.map(user => user.name);

console.log(names); // Output: ['John', 'Tom', 'Mathew']

forEach method

The forEeach method in JavaScript is an array method used to execute a provided function once for each element in an array. It’s beneficial when you want to perform side effects such as logging, updating each element in place, or calling functions that do not require returning a new array.

Syntax:


array.forEach(function(element, index, array) {
  // Your code here
}, thisArg);

element: The current element being processed in the array.

index (optional): The index of the current element being processed.

array (optional): The array forEach was called upon.

thisArg (optional): A value to use as this when executing the callback function.

Characteristics of forEach

1. Does Not Return a Value: The forEach method always returns undefined. It doesn’t return a new array, unlike some other array methods like map.

2. Iterates Over Every Element: The function passed to forEach is executed for every element of the array, even if it is undefined, null, or an empty slot.

3. Cannot Be Interrupted: You cannot break out of a forEach loop using break or continue. If you need to stop iteration based on a condition, consider using a for loop or the some or every methods.

4. Modifying the Array: You can modify the original array within the forEach loop by directly altering its elements.

Example: Modify the array element


const numbers = [1, 2, 3, 4];
numbers.forEach((num, index, arr) => {
    arr[index] = num * 5; // multiply by 5 for each element in the original array
});
console.log(numbers); // Output: [5, 10, 15, 20]

find() method

In JavaScript, find methods is used to search for elements in an array based on a given condition.

KeyPoints:

1. The find method returns the value of the first element in the array that satisfies the provided testing function.

2. It returns the first element that matches the condition. If no elements match, it returns undefined.

Example:

1. Filtering Even Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const data = numbers.find(num => num % 2 === 0);
console.log(data); // Output: 2

2. Filtering string from the array


const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.find(fruit => fruit== 'Orange');
console.log(filteredData); // Output: Orange

3. Filtering Objects in an Array


const employees = [
  { name: 'John', age: 38 },
  { name: 'Tom', age: 37 },
  { name: 'Mathew', age: 35 },
  { name: 'Andrew', age: 30 },
];

const data = employees.find(employee => employee.age > 36);
console.log(data); // Output: { name: 'John', age: 38 }

filter() method

In JavaScript, filter is an array method used to search for elements in an array based on a given condition.

Key Points

1. The filter method creates a new array containing all elements that pass the test implemented by the provided function.

2. It returns an array of all elements that satisfy the condition. If no elements match the condition, it returns an empty array.

Example:

1. Filtering Even Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const evenNumbers = numbers.filter(num => num % 2 === 0);
console.log(evenNumbers); // Output: [2, 4, 6, 8 ,10]

2. Filtering Odd Numbers:


const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 10];
const oddNumbers = numbers.filter(num => num % 2 !== 0);
console.log(evenNumbers); // Output: [1, 3, 5, 7]

3. Filtering string from the array


const fruits = ['Apple', 'Banana', 'Orange'];
const filteredData= fruits.filter(fruit => fruit== 'Orange');
console.log(filteredData); // Output: ['Orange']

4. Filtering Objects in an Array


const employees = [
  { name: 'John', age: 38 },
  { name: 'Tom', age: 37 },
  { name: 'Mathew', age: 35 },
  { name: 'Andrew', age: 30 },
];

const data = employees.filter(employee => employee.age > 36);
console.log(data); // Output: [ { name: 'John', age: 38 }, { name: 'Tom', age: 37 } ]

JavaScript if else statement

In JavaScript, if, else, and else if are control flow statements that allow you to execute certain blocks of code based on specific conditions. These statements help you make decisions in your code.

1. if Statement

The if statement is used to execute a block of code if a specified condition is true.

Syntax:


if (condition) {
    // Code to execute if the condition is true
}

Example:


let age = 21;
if (age >= 21) {
    console.log("Age of boy adult.");
}

In this example, the message “Age of boy adult.” will be logged to the console because the condition age >= 21 is true.

2. else Statement

The else statement is used to execute a block of code if the if condition is false.

Syntax:


if (condition) {
    // Code to execute if the condition is true
} else {
    // Code to execute if the condition is false
}

Example:


let age = 20;
if (age >= 21) {
    console.log("You are an adult.");
} else {
    console.log("You are not an adult.");
}

In this example, the message “You are not an adult.” will be logged to the console because the condition age >= 21 is false.

else if Statement

The else if statement allows you to check additional conditions if the previous if condition is false. You can chain multiple else if statements together.

Syntax:


if (condition1) {
    // Code to execute if condition1 is true
} else if (condition2) {
    // Code to execute if condition1 is false and condition2 is true
} else {
    // Code to execute if both condition1 and condition2 are false
}

Example:


let score = 85;

if (score >= 90) {
    console.log("Grade: A");
} else if (score >= 80) {
    console.log("Grade: B");
} else if (score >= 70) {
    console.log("Grade: C");
} else {
    console.log("Grade: F");
}

In this example, the message Grade: B will be logged to the console because the condition score >= 80 is true, and the conditions before it are false.

JavaScript comparison

JavaScript comparison operators are used to compare two values and return a boolean value (true or false) based on the comparison. These operators are essential in controlling the flow of a program, especially in conditional statements like if, while, and for loops.

1. Equality (==) Operator

Compares two values for equality after converting them to a common type (type coercion).

Returns true if the values are equal, otherwise false


10 == "10";     // true (number 10 is coerced to string "10")
20 == 20     // true (number 20 is coerced to number 20)

2. Strict Equality (===)

Compares two values for equality without performing type conversion. Both value and type must be the same.


10 === "10"; // false
10 === 10;   // true

3. Inequality (!=)

Compares two values for inequality without performing type conversion.


10 !== "10"; // true
10 !== 10;   // false

4. Strict Inequality (!==)

Compares two values for inequality without performing type conversion.


10 !== "10"; // true
10 !== 10;   // false

5. Greater Than (>)

Returns true if the left operand is greater than the right operand.


10 > 5; // true

6. Greater Than or Equal To (>=)

Returns true if the left operand is greater than or equal to the right operand.


10 >= 10; // true

7. Less Than (<)

Returns true if the left operand is less than the right operand.


5 < 10; // true

8. Less Than or Equal To (<=)

Returns true if the left operand is less than or equal to the right operand.


5 <= 5; // true

9. Ternary Operator (? :)

A shorthand for an if-else statement. It takes three operands: a condition, a value if true, and a value if false.


const result = (10 > 5) ? "Yes" : "No"; // "Yes"

JavaScript Comments

JavaScript comments are annotations in the code that are ignored by the JavaScript engine when the code is executed. They are used to explain code, make notes, or temporarily disable certain parts of the code. Comments are helpful for both the developer writing the code and others who might read or maintain the code in the future.

There are two types of comments

Single-Line Comments

Single-line comments are used to add short notes or explanations on one line.

They start with // and extend to the end of the line.


// This is a single-line comment
let name = 'John'; // Variable name is assigned the value John

Multi-Line Comments

Multi-line comments are used for longer explanations or for commenting out multiple lines of code.

They start with /* and end with */


/*
This is a multi-line comment.
It can span multiple lines.
It is useful for longer descriptions or temporarily disabling blocks of code.
*/
let x = 10;

JavaScript Syntax

JavaScript syntax refers to the set of rules that define how a JavaScript program is written and interpreted by the browser or JavaScript engine.

1. Variables

Used to store data values.

Declared using var, let, or const.


var x = 10;
let y = 20;
const name = "John";

2. Semicolons

Although semicolons are often optional, it is recommended to use them to terminate statements to avoid potential issues caused by JavaScript’s automatic semicolon insertion.


let x = 5;
let y = 10;

3. Automatic Type Conversion (Coercion)

JavaScript automatically converts data types when performing operations between different types (e.g., adding a number to a string).


let result = 5 + "5"; // "55" (number 5 is converted to string)

4. Identifiers

Identifiers are names given to variables, functions, and objects. They must start with a letter, underscore (_), or dollar sign ($), followed by letters, digits, underscores, or dollar signs.


let name = "John";
let $numValue = 100;
let _isUserAllowed = true;

we can’t declare a variable that starts with a number.


let 1name = "John";  // not allowd

5. Reassigning Variables

Variables declared with var or let can be reassigned.

Variables declared with const cannot be reassigned.


let a = 10;
a = 20; // Valid

const b = 50;
// b = 100; // Error: Assignment to constant variable.

spread operator

The spread operator (...) in JavaScript is a versatile and powerful feature that allows you to expand or spread elements in arrays, objects, or function arguments. It’s commonly used for copying, merging, and passing around data structures without modifying the original ones.

the use of spread operator in Array

Copying an Array:


const arr1 = ["Apple","Banana", "Orange"];
const arr2 = [...arr1];
console.log(arr2); // Output: [Apple,Banana,"Orange]

Combining Arrays


const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const combined = [...arr1, ...arr2];
console.log(combined); // Output: [1, 2, 3, 4, 5, 6]

Adding Elements to an Array:


const arr1 = [1, 2, 3];
const arr2 = [0, ...arr1, 4];
console.log(arr2); // Output: [0, 1, 2, 3, 4]

the use of the spread operator in Object

Copying an Object


const obj1 = { name: 'John', age: 38 };
const obj2 = { ...obj1 };
console.log(obj2); // Output: {name: 'John', age: 38}

Merging Objects


const obj1 = { name: 'John', age: 38 };
const obj2 = { sex: 'Male', qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 38, sex: 'Male', qualification: 'Graduate' }

Overriding Properties


const obj1 = { name: 'John', age: 38 };
const obj2 = { age: 39, qualification: 'Graduate'};
const merged = { ...obj1, ...obj2 };
console.log(merged); // Output: {name: 'John', age: 39, qualification: 'Graduate' }

Function Arguments

Spreading an Array as Arguments


function sum(a, b, c, d) {
  return a+b+c+d;
}
const numbers = [1, 2, 3,4];
console.log(sum(...numbers)); // Output: 10

Javascript Hoisting

Javascript Hoisting is a mechanism that moves all variable and function declarations to the top of their scope before code execution. However, variable assignments still happen where they originally were.
Note:- variable declaration is hoisted while the assignment remains in the same place.


console.log(emp_name);
var emp_name = "John";
Output:-
undefined

Note:- undefined means value is not defined in the variable.

Hoisting Process of above code

Now, the javascript hoisting mechanism run the above code into 3 steps
step1:- firstly declare emp_name variable


var emp_name

step2:- Now run the console.log


console.log(emp_name);

step3:- Now defined the emp_name value


emp_name = "John";

Complete hoisting process of the above code


var emp_name
console.log(emp_name);
emp_name = "John";
Output:-
undefined

call the variable after defined the value


var emp_name; // → Hoisted variable declaration
console.log(emp_name); // → undefined
emp_name = "John"; // → variable assignment remains in the same place
console.log(emp_name); // → John
Output:-
undefined
John

Hoisting Rule does not work when used ‘use strict’ before the code


'use strict';
console.log(emp_name); 
emp_name = 'John'; 
Output:-
Uncaught ReferenceError: emp_name is not defined

Javascript Hoisting Rule for function

function declarations are hoisted to the top of their scope.


display_name();
function display_name() {
  var emp_name='John'
    console.log('Hello '+emp_name);
}
Output:-
Hello John

Hosting process of the function of the above code


function display_name() {
  var emp_name='John'
    console.log('Hello '+emp_name);
}
display_name();

Javascript Hoisting Rule does not work for function expression


display_name();
var display_name= function() {
  var emp_name='John'
  console.log(emp_name);
}
Output:-
Uncaught TypeError: display_name is not a function

Javascript Closure function

Closure function is a part of advanced javascript, It is basically used to access outer function parameters and variables in the inner function so this inner function is called closure function.
the inner function returns into the outer function.

Suppose, you have a outer function start() and declared employeeName variable in this and called this variable into displayEmployeeName() inner function.


function start() {
  var employeeName = 'John'; // employeeName is a local variable created by start function
  function displayEmployeeName() { // displayEmployeeName() is the inner function, a closure
    console.log("Hello "+employeeName); // employeeName variable declared in the parent function
  }
  displayEmployeeName();
}
start();
Output:-
Hello John

Suppose, you have defined x variable value into the outer scope and captured the x variable value into inner scope function getNum()


var x = 5; // declaration in outer scope
function getNum() {
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 5 to console
Output:-
5

Suppose, You change the outer scope variable x value into the inner function scope then the value will be change.


var x = 5; // declaration in outer scope
function getNum() {
x=2;
console.log(x); // outer scope is captured on declaration
}
getNum(); // prints 2 to console
Output:-
2

Javascript Object Deep copy

Javascript Object deep copying means that the value of the new variable is disconnected from the original variable.
You can create the deep copying through JSON.parse method with JSON.stringify

Syntax:-


let new_object_name = JSON.parse(JSON.stringify(object_name));

Example:- Suppose you have employee object and copy object through JSON.parse() method with JSON.stringify into new_employee object then you change the firstName, city and state in new_employee object then it will not connected to old employee object.


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'Maharashtra',
        country: 'India'
    }
};


let new_employee = JSON.parse(JSON.stringify(employee));
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // disconnected
new_employee.address.state = 'Delhi'; // disconnected
console.log(new_employee);
console.log(employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “Mumbai”, state: “Maharashtra”, country: “India”}

}

Javascript Object shallow copy

A Javascript shallow copy means that the primitive datatype value of the new variable is disconnected from the original variable and the compositive datatype value of the new variable is connected from the original variable.

You can create shallow copy through the below methods.

1) Object.assign(target_object,source_object);
2) through spread operator

1) Copy through Object.assign() method

Syntax:-


var new_object=Object.assign({},object)

Example:-
Suppose, You have an employee object and copy object through Object.assign() into new object new_employee


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'maharashtra',
        country: 'India'
    }
};


let new_employee = Object.assign({}, employee);
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}

}

2) Copy through spread operator

Syntax:-


var new_object={...Object};

Example:-
Suppose, You have an employee object and copy object through spread operator (…) into new object new_employee


let employee = {
    firstName: 'John',
    lastName: 'Taylor',
    address: {
        city: 'Mumbai',
        state: 'maharashtra',
        country: 'India'
    }
};


let new_employee = {...employee};
new_employee.firstName = 'Rom'; // disconnected
new_employee.address.city = 'New Delhi'; // connected
new_employee.address.state = 'Delhi'; // connected
console.log("newEmployee:-",new_employee);
console.log("oldEmployee:-"employee);
Output:-
newEmployee:- {
firstName: “Rom”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}
}

oldEmployee:- {
firstName: “John”
lastName: “Taylor”
address: {city: “New Delhi”, state: “Delhi”, country: “India”}

}

JavaScript Arrow function

Javascript Arrow function came into ES6 (ECMAScript 6). Arrow functions don’t bind this keyword to the object.
Arrow functions are best for callbacks or methods like map, reduce, or forEach, etc.

in Arrow function do not write function keyword.

Arrow function without parameter

Syntax:-


arrow_function_name:()=>{
return 'Hello';
}

Example:- Suppose, you have a greetings object and that has the say_hello method without parameter..


let greetings={
say_hello:()=>{
return 'Hello';
}
}
console.log(greetings.say_hello());
Output:-
Hello

Arrow function with parameters

Syntax:-


arrow_function_name:(param1, param2)=>{
return param1+param2;
}

Example:- Suppose, you have a greetings object and that has the say_hello method with parameter friend_name.


let greetings={
say_hello:(friend_name)=>{
return 'Hello '+friend_name;
}
}
console.log(greetings.say_hello('Rom'));
Output:-
Hello Rom

Arrow function do not bind this keyword to the object

Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show undefined.


let employee = {
  first_name: 'John',
  last_name:'Taylor',
  full_name: () => { 
    console.log(this.first_name+' '+this.last_name)  
  }
}
employee.full_name();
Output:-
undefined undefined

Simple function bind this keyword to the object

Suppose, you have employee object and you want to call first_name and last_name through this keyword in full_name method then output will show first_name and last_name values.


let employee = {
  first_name: 'John',
  last_name:'Taylor',
  full_name: function () { 
    console.log(this.first_name+' '+this.last_name)  
  }
}
employee.full_name();
Output:-
John Taylor

Javascript Non enumerable property

Javascript Non-enumerable property is used when you do not want to reassign the value of the key of the object. The non-enumerable property of the object does not show when you iterate through the object using for…in loop or using Object.keys() to get an array of property names.


var employee = {
  name: 'John'
};
employee.salary = '$2000';
employee['country'] = 'USA';

console.log(Object.keys(employee)); // ['name', 'salary', 'country']

As we know that employee object properties name, salary, country are enumerable hence it’s shown up when we called Object.keys(employee).

How to create non-enumerable property of the object?

To create a non-enumerable property we have to use Object.defineProperty() and defined enumerable:false. This is a special method for creating a non-enumerable property in JavaScript.


// Create non-enumerable property
Object.defineProperty(employee, 'phoneNo',{
	value : 3333333333,
	enumerable: false
})

console.log(Object.keys(employee));
Output:- [‘name’, ‘salary’, ‘country’]

Note:- phoneNo is not showing in the output because it is a non-enumerable property.

Now let’s try to change value of phoneNo


employee.phoneNo = 4444444444; 
console.log(employee.phoneNo);
Output:- 3333333333

Note:- phoneNo value will not change and show old value.

How to empty an array list in JavaScript?

There are several ways to empty an array in JavaScript. Here are some common methods:

1. Assign an Empty Array

You can assign a new empty array to the variable, effectively replacing the original array with an empty one.
Syntax:-


var arrayList=[];

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced arrayList by another variable
array_list = []; // Empty the array  
console.log(array_list); //Output []
console.log(new_array_list); // Output ['a', 'b', 'c', 'd', 'e', 'f']

Note:- if you changed original array variable then reference array will remain unchanged.

2. Set the Length to Zero

Setting the length property of the array to 0 will clear all elements.

Syntax:-


var arrayList.length=0;

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced array_list by another variable
array_list.length = 0; // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []

Note:- This way of empty the array also update all the reference variable which pointing to the original array.

3. Use the splice() Method 

You can use the splice() method to remove all elements from the array.
Syntax:-


arrayList.splice(0, arrayList.length);

Example:-


var array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
var new_array_list = array_list;  // Referenced array_list by another variable
array_list.splice(0, array_list.length); // Empty the array by setting length to 0
console.log(array_list); // Output []
console.log(new_array_list); // Output []

4. Pop Elements Until Empty

You can use a loop to pop elements from the array until it is empty. This method might not be as efficient as others but works effectively.


let array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
while (array_list.length > 0) {
    array_list.pop();
}
console.log(array_list); // Outputs: []

5. Shift Elements Until Empty

Similar to pop, you can use a loop to shift elements from the front of the array until it’s empty.


let array_list = ['a', 'b', 'c', 'd', 'e', 'f']; // Created array
while (array_list.length > 0) {
    array_list.shift();
}
console.log(array_list); // Outputs: []

How to reverse string in Javascript?

Reversing a string in JavaScript involves creating a new string with the original string’s characters in the opposite order. This can be achieved by converting the string into an array, reversing the array, and then joining the array back into a string.

If you want to reverse string in javascript then use the reverse() method


var string = "Welcome to Javascript!";
console.log(string.split("").reverse().join(""));
Output:-
!tpircsavaJ ot emocleW

Reverse string without pre defined function


var string = "Welcome to Javascript!";
var arr= string.split("");
var i=0;
var new_arr=[];
for(i=arr.length-1; i>=0; i--){
  new_arr.push(arr[i]);

}
console.log(new_arr.join(""));
Output:-
!tpircsavaJ ot emocleW

Reverse only string words


var string = "Welcome to Javascript!";
let data= string.split(" ");
let revdata=[];
for(let i=0; i<(data.length); i++)
{
 revdata.push(data[i].split("").reverse().join(""));

}	
console.log(revdata.join(" "));
Output:-
emocleW ot !tpircsavaJ

Javascript Array

In JavaScript, an array is a special type of object used to store multiple values in a single variable. Arrays are ordered collections, meaning the values (called elements) are stored in a sequence, and each element can be accessed by its numerical index.

OR

Array is used to store more than one value into single variable.


var arr=["John","Rom","Mathew"];

How to create an Array?


var item=[item1, item2,item3......itemn];

Example:-


var users=["John","Rom","Mathew"];

Creating a Array through new keyword


var users= new Array('John','Rom','Mathew');

First element of Array position is zero.


var users= new Array('John','Rom','Mathew');
console.log(users[0]) //Output:- John

Add element into the Array

push() method:- this method is used to store element into the Array.

Example:-


users=["John","Rom","Mathew"];
users.push("Clerk");
console.log(users);  //Output:- ["John", "Rom", "Mathew", "Clerk"]

Try it Yourself


 numbers=[10,20,30];
 numbers.push(40);
 console.log(numbers) //Output:- [10,20,30,40];

Note:- push() method is used to add element after the last element of the Array.

unshift() method:- this method is also used to add element before the first element of the Array.


users=["John","Rom","Mathew"];
users.unshift("Clerk");
console.log(users);  //Output:- ["Clerk", "John", "Rom", "Mathew"]

Try it Yourself


numbers=[10,20,30];
numbers.unshift(40);
console.log(numbers) //Output:- [40,10,20,30];

Remove element from the Array

pop() method:- this method is used to remove last element from the Array.

Example:-


users=["John","Rom","Mathew"];
users.pop();
console.log(users);  //Output:- ["John", "Rom"]

Try it Yourself


numbers=[10,20,30];
numbers.pop();
console.log(numbers) //Output:- [10,20];

shift() method:- this method is used to remove the first element from the Array.

Example:-


users=["John","Rom","Mathew"];
users.shift();
console.log(users);  //Output:- ["Rom","Mathew"];

Try it Yourself


 numbers=[10,20,30];
 numbers.shift();
 console.log(numbers) //Output:- [20,30];

Modify Array’s element value


users=["John","Rom","Mathew"];
console.log(users);  //Output:- ["John",Rom","Mathew"];

Example:- Now change the Rom to Andrew


 users=["John","Rom","Mathew"];
 users[1]="Andrew";
 console.log(users); // ["John","Andrew","Mathew"];

How to check variable is Array or not?

Array.isArray() function is used to check variable is Array or not.


users=["John","Rom","Mathew"];
var check_array=Array.isArray(users);
console.log(check_array);  //Output: true

Try it Yourself


  var name="John";
  var check_name=Array.isArray(name);
  console.log(check_name);  //Output: false

How to count the Array length?

length is used to count the total number of elements in the Array.


var arr=["John","Rom","Andrew","Smith"]
console.log(arr.length);  //4

Try it Yourself

Sorting Array

You can sort the Array element(which is numeric) Ascending and Descending order.

Ascending Order:-


  var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return a-b;
});
console.log(sort_arr);  
Output:- [3,5,7,10,12,15];

Descending Order:-


 var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return b-a;
});

console.log(sort_arr);  
Output:- [15,12,10,7,5,3];

Javascript String

In JavaScript, a string is a sequence of characters used to represent text. Strings are one of the fundamental data types in JavaScript and are commonly used to store and manipulate textual data.

String can be enclosed in Single Quotes like ‘john’ or Double Quotes like “john” or backtics (which came into ES6) like `john`.


var first_name ='John';
var last_name="Taylor";
var email=`john@abc.com`;

Note:- backtics is basically used to combined variable value and strings.

Example:- Now you add first_name and last_name along with Hello string.


var full_name=`Hello ${first_name} ${last_name}`;
console.log(full_name);  // Output:- John Taylor

Create a String:-

1) String():- You can create string through String function.


var age=35;
var age_string=String(age);  
console.log(age_string);  // Output:- "35"

var bool =true;
var bool_string=String(bool) // Output:- "true"

2) toString():- toString() is used to convert data into string.


var age =35;
var age_string=age.toString(); // Output "35";

var bool =true;
var bool_string=bool.toString() // Output:- "true"

3) creating a String Object through new keyword and it behaves like Object


var string_object = new String("John");
console.log(typeof string_object); //output:- "object" 

Concat two or more strings:- 1) You can concat the two string through + sign


var first_name="John";
var last_name="Taylor";
document.write(first_name + last_name); //Output:- JohnTaylor
document.write(first_name +' '+last_name); //Output:- John Taylor

Try it Yourself

2) You can concat strings through concat() keyword.


var first_name="John";
var last_name="Taylor";
document.write(first_name.concat(last_name)); //Output:- JohnTaylor

Try it Yourself

3) Concat string through backtics


var first_name="John";
var last_name="Taylor";
document.write(`${first_name} ${last_name}`); //Output:- John Taylor

Try it Yourself

trim() method:- this method is used to trim the white space from the string.


var name=" John ";
console.log(name.trim());  //Output:- John

split() method:- It is used to split a string into Array


var str="John went to college";
var str_arr=str.split(" ");
document.write(str_arr[0]);   // Output:- John
document.write(str_arr[1]);   // Output:- went
document.write(str_arr[2]);   // Output:- to
document.write(str_arr[3]);   // Output:- college

Try it Yourself

join() method:- It is used convert Array into String


arr=["John", "went", "to", "college"];
arr_to_string= arr.join("-");
document.write(arr_to_string);  // Output:- John-went-to-college

Try it Yourself

Reverse a string:-


var str="John Taylor"
let rev_string= str.split('').reverse().join('');
document.write(rev_string);  // Output:- rolyaT nhoJ

Try it Yourself

Javascript Variable

A JavaScript variable is a named container used to store data values. Variables allow you to store information that can be referenced and manipulated within your program.

JavaScript variable Syntax


(typeOfVariable) variableName = variableValue

Define a variable:- in the below example, variableName name assigned value John


var name="John";

Using a variable:- Now, You can use variable name in the file.


 console.log(name); //John

Note:- If you did not define the variable type then it will work as like var variable,


name="John";
console.log(name); //John

There are two types of JavaScript variable
1) local variable
2) Global variable

1) Local variable:- A variables declared in a function, become LOCAL variable to the function. Local variables have Function scope: They can only be accessed from within the function.


function user() {
  var name = "John";
  console.log(name);
}
	    
user();
console.log(name);  

Note:- When we call console.log(name) after the function user() call then output will be blank.

2) Global Variables:- A variable declared outside a function, becomes GLOBAL variable. A global variable has global scope: All scripts and functions on a web page can access it.


var name = "John";

function myFunction() {

  console.log(name)  
}


Javascript Variable Declaration

JavaScript variable declaration is the process of creating a variable and optionally assigning it an initial value. When you declare a variable, you inform the JavaScript interpreter to reserve memory space for that variable and optionally initialize it with a value.

var, let and const are used to variable declaration in JavaScript. let and const are introduced in ECMAScript (ES6). before introduced let and const only var is used to variable declaration.
var is used for function scope while let is used to block scoped.

Example:- function scoped


for(var i=1; i<5; i++){
  console.log(i);
 }

console.log("i value is ",i);  //output:- i value is 5

Example:- block scoped


 for(let i=1; i<5; i++){
   console.log(i);  //output:- 1 2 3 4 5
  }

 console.log("i value is ",i); 

Output:- Uncaught ReferenceError: i is not defined

Note:- above example i is block scoped so it will show output in the for loop when you call i after the loop then it will show error.

const declaration:- You can not reassign the value in the const variable.

Example:- If you reassign the value in the premitive datatype then it will show error.


const name="John";
console.log(name); 
Output:-John

Now, change the name from John to Rom.


name="Rom";
console.log(name);


Output:-Uncaught TypeError: Assignment to constant variable.

Example:- If you want to reassign the value into array element then value will be update.


const arr=[1,2];
arr[1]=3;
console.log(arr) //Output:- [1,3]

If we can not reassign in const then why use in for of and for in loop?
it seems that they create a new block scope with each iteration. That would mean that each new index is actually a new variable within a new scope & our constant is never reassigned.


var data=[{name:"John", age:35},{name:"Rom", age:30}] 

for( const element of data){
	
	console.log(element.name);  
} 

Output:- John
Rom

Javascript Datatype

JavaScript has basically two type of datatypes
1) Primitive Datatype
2) Composite Datatype

1) Primitive Datatype:- These type of datatype is immutable and it do not have properties. When you make a copy, it will be a real copy.

Example:- when you reassign a new value to b, the value of b changes, but not of a.


 <script>
 const a = "John";
 let b = a   // this is the copy
 b = "Rom";
 document.write(b) // Rom
 document.write(a) // John
 </script>

Try it Yourself

1) String:- It is basically used to store string value and string value represents through single quote or double quotes.


 var name="John";
 console.log(typeof name);  //string

2) Number:- It is used to store number value.


 var age=35;
 console.log(typeof age);  //number

3) undefined:- A variable that has not value is undefined.


  var name;
  console.log(typeof name); // undefined 

4) Null:- It has null value.


 var nothing = null;
 console.log(nothing);

5) Boolean:- this datatype variable has value true or false.


 var is_loggedin=true;
 console.log(is_loggedin);  //true

 var not_loggedin=false;
 console.log(not_loggedin);  //false

6) Symbol:- It came into ECMAScript6 (ES6). It represents a unique identifier.

2) Composite Datatype:- Object, Array and methods are compositive datatypes. Technically, arrays are also objects, so they behave in the same way. These values are actually stored just once when instantiated, and assigning a variable just creates a pointer (reference) to that value.

Object Example:-


 var users={
      name:"John",
      age:35
        }

 console.log(typeof users) //Object

Array Example:-


 var users=[{
       name:"John",
       age:35
       }]

 console.log(typeof users) //Object

Example:- Now, if we make a copy b = a , and change some nested value in b, it actually changes a’s nested value as well, since a and b actually point to the same thing.


 <script>
 const a = {name:'John'}
 const b=a;
 b.name='Rom';
 document.write(a.name);  //Output:- Rom
 document.write(b.name);  //Output:- Rom
 </script>
 

Try it Yourself

Javascript Array Sorting

You can sort the Array element (which is numeric) in Ascending or Descending order through below code.

Ascending Order:- There are two ways to Sorting in Ascending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j-1] > arr[j]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:-[3,5,7,10,12,15];

2) Array Sorting with sort() function


  var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return a-b;
});

console.log(sort_arr);  

Try it Yourself

Output:- [3,5,7,10,12,15];

Descending Order:- There are two way in descending Order.

1) Array Sorting without function


var arr=[10,5,7,3,12,15];
var temp;
let i;
let j;
for( i=0; i<arr.length; i++)
{
for(j=i; j>0; j--){

  if(arr[j] > arr[j-1]){
        
        temp=arr[j];
        arr[j]=arr[j-1];
        arr[j-1]=temp;

		}
	}
}
console.log(arr);

Try it Yourself

Output:- [15,12,10,7,5,3];

2) Array Sorting with sort() function


 var arr=[10,5,7,3,12,15];
  var sort_arr=arr.sort(function(a,b){

	return b-a;
});

console.log(sort_arr);  

Try it Yourself

Output:- [15,12,10,7,5,3];

Javascript Object

In JavaScript, an object is a complex data structure that allows you to store collections of key-value pairs. Objects are one of the core components of JavaScript and are used to represent real-world entities, such as a user, a car, or any other item that has properties and behaviors.

OR

Object is used to store multiple values. object has key and value pair.

Characteristics of JavaScript Objects

Key-Value Pairs: Each item in an object is stored as a key-value pair, where the key is a string (or Symbol) that identifies the property, and the value can be any data type (string, number, array, function, etc.).

Properties and Methods: The values associated with keys in an object are called properties if they are data and methods if they are functions.

 


var obj={name:"John",age:35,sex:"Male"}

You can define multiple objects into the Array. you can say these are Array Object.


var users_details=[{name:"John",age:35,sex:"Male"},
      {name:"Rom",age:30,sex:"Male"},
      {name:"Neena",age:25,sex:"female"}
    ]

define the method into the Object


   var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35,
     full_name: function() {
       return this.first_name + " " + this.last_name;
   }

   }

Note:- full_name is a method in the user_details Object.

get the Object key value

Suppose you have user_details Object and you want to get the key value


     var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35,
     full_name: function() {
       return this.first_name + " " + this.last_name;
   }

   }

Example:- get the user’s full_name and age.


console.log(user_details.full_name);
Output:- John Taylor

get the age of the user


console.log(user_details.age);
Output:- 35

Add key value into the Object

Suppose you have user_details Object


 var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

Now, you want to add user_id into the user_details Object


 user_details.user_id=1234

Now get the user_details value


console.log(user_details);
Output:-{first_name: “John”, last_name: “Taylor”, age: 35, user_id: 1234}

Try it Yourself

Update key value into the Object

Suppose you have user_details Object


var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

Now, you have to update age into the user_details Object


 user_details.age=36

Now get the user_details value


console.log(user_details);
Output:-{first_name: “John”, last_name: “Taylor”, age: 36}

Delete the key value from the Object

Syntax:-


delete object.key

Example:- delete the age key value from the Object


     var user_details={
     first_name:"John",
     last_name:"Taylor",
     age:35
   }

   delete user_details.age;

   console.log(user_details);

Output:-{first_name: “John”, last_name: “Taylor”}

Try it Yourself

Get the Object key value through for in loop

Syntax:- get the Object value


for (var key in Object){
	
 console.log(Object[key]);

}

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Get the users object value


for (var key in users){
	
	console.log(users[key]);

}
Output:-1
John
Taylor
35

Try it Yourself

How to check Object key is exists or not

Syntax:-



object_name.hasOwnProperty(object_key);  //Output true or false

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now check the key is exists or not


users.hasOwnProperty("first_name");  //Output true

users.hasOwnProperty("email");  //Output false

Try it Yourself

How to get the Object’s keys

Syntax:-



Object.keys(object_name);  

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now you want the all users object keys



Object.keys(users);  

Output:-[“id”,”first_name”,”last_name”,”age”]

Try it Yourself

How to get the Object’s values

Syntax:-



Object.values(object_name);  

Example:- Suppose you have users object.


let users={
	id:1,
	first_name:"John",
	last_name:"Taylor",
	age:35
}

Now you want the all users object values



Object.values(users);  

Output:-[1, “John”, “Taylor”, 35]

Try it Yourself

Javascript for loop

for loop is used to get the array value.


for(var i=0; i<5; i++){
	
console.log(i);

}
Output:- 0 1 2 3 4

get the Array value

Suppose you have emp array


var emp=["John","Rom","Mathew","Sachin"];

Now, get the Array value


for(var i=0; i < emp.length; i++){
	
	console.log(emp[i]);

}
Output:- John Rom Mathew Sachin

Note:- emp.length is used to count the number of array element.

get the array element value from last element to first element.


var emp=["John","Rom","Mathew","Sachin"];
for(var i=emp.length-1; i >= 0; i--){
	
	console.log(emp[i]);

}
Output:- Sachin Mathew Rom John

Changes the increment


for(var i=0; i<=10; i=i+2)
{

	console.log(i);
}
Output:- 0 2 4 6 8 10

Javascript for of loop

This loop came into the ES6. It is basically used to get the iteration value from the Array.
Syntax:-


for (variable of iterable) {
  // logic 
}

Example:-


var arr=[10,20,30];
for (var element of arr){
	
 console.log(element);
}
Output:- 10 20 30

Try it Yourself

Note:- you can use var, let and const to get the iteration value.

get the iteration value from the string


var data="John";
for( let element of data){

  console.log(element);

}
Output:- J
o
h
n

get the iteration value from the Array Object


var data=[{name:"John", age:35},{name:"Rom", age:30}]
for( var element of data){
	
	console.log("My name is "+element.name+" and age is "+element.age);

}
Output:-
My name is John and age is 35
My name is Rom and age is 30

Javascript for in loop

It is used to get the iteration value from the object.

Syntax:-


for (variable in iterable) {
  // logic 
}

Example:- get the user object key’s value.


var user ={name:"John",age:35,sex:"Male"}
for(var element in user){
	
 console.log(user[element]);
}
Output:- John 35 Male

Try it Yourself

Get the object’s keys


var user ={name:"John",age:35,sex:"Male"}
for(var element in user){
	
	console.log(element);
}
Output:- name age sex

Javascript While loop

This loop will execute until the condition is given false.

Syntax:-


while(condition){
	
	// logic implement
}

Example:- Now, you have to print the i value until the i value not more than 20.


var i=0;
while(i<=20){
	
	console.log(i);
	i++;
}
Output:-
0
1
.
.

19
20

Example:- Now, you have to print the even i value until the i value not more than 10.


var i=2;
while(i<=10){
  
  if(i%2 ==0){
    console.log(i);
  }
  
  i++;
}
Output:-
2
4
6
8
10

Javascript do while loop

Do while loop run at least once because it checked at the end of the iteration.

Syntax:-


 do{
   // logic
} while(condition)

Example:-


var i=1
do{
	
 console.log(i);
  i++;

}while(i<5);
Output:-
1
2
3
4
5

Javascript Function

Function is basically used to reusable the code. A function is executed when you call it.

Syntax:-


function functionName(parameters){
	
	// logic implement

}

Example:- Suppose you define employeeDetails function which has two parameters name and age.


function employeeDetails(name, age){
  
  console.log("my name is "+name+" and my age is "+age);

}

How to call a function?

You have already defined the function after that you can call the function multiple times based on your requirements.


employeeDetails("John",35);  //my name is John and my age is 35

employeeDetails("Rom",30);  //my name is Rom and my age is 30

What is Function Scoping?

Everything defined in the function can not be access outside the function, this is called function scoping.


function user(){
	
	var emp_name="John";
	console.log(emp_name);  
}
Output:- John

function user(){
	
	var emp_name="John";

}
console.log(emp_name);    
Output:- reference error

What is Immediately Invoke function?

When the function call itself, it is called Immediately Invoke function.

Syntax:-


(function() {
 
// logic

})();

Example:-


(function() {

console.log("Hello");

})();
Output:- Hello

Javascript Function expression

Firstly create a function after that defined into the variable is called function expression.

Syntax:-


var variableName=function(){
}

Note:- You can declare variable through let, var and const according to your requirements.

Example:- Suppose, You create a function and defined into userName variable.


var userName = function() {
  console.log('Hello John');
};

Now, call the userName


userName();
Output:- Hello John

Note:- function expression does not follow Hoisting Rule while Normal function follows the Hoisting Rule.

If you call the function first after that defined the function expression then it will show error.

Example:- Firstly call the userName() function after that defined the userName function expression.


userName();
var userName = function() {
  console.log('Hello John');
};
Output:- Uncaught TypeError: userName is not a function

Normal function follows the Hoisting Rule

Step1:- Firstly call the normal function after that defined userName() function.


userName();
function userName() {
  console.log('Hello John');
};
Output:- Hello John

Step2:- Firstly defined the function after that call the function userName() function.


function userName() {
  console.log('Hello John');
};
userName();
Output:- Hello John

Javascript Constructor function

Constructor function is used to create the Object through new keyword.
First character of the constructor function should be in Capital letters.

Syntax:-


function FunctionName(){
	
	// logic implement

}

var obj = new FunctionName();

Example:- Suppose, You have to create Employee() constructor function.


function Employee(){
	
this.firstName="John";
this.lastName="Mathew";
this.email="john@abc.com";
}

// Now, create the Object

var emp= new Employee();
console.log(emp.firstName);
console.log(emp.lastName);
console.log(emp.email);
Output:- John
Mathew
john@abc.com

Note:- this property reference to the constructor function.

Adding Method in Constructor function

Now you want to add method fullName() in the constructor function.


function Employee(){
     
this.firstName="John";

this.lastName="Mathew";

this.fullName= function(){
	
	return this.firstName+" "+this.lastName;
}

}

Now, create the object



var emp = new Employee();

console.log(emp.fullName())
Output:- John Mathew

Parameters pass in the constructor function

You can pass multiple parameters in the function according your requirements.

Syntax:-


function FunctionName(parameter_1, parameter_2,....parameter_n){
	
	// logic implement

}

var obj = new FunctionName(parameter_1, parameter_2,....parameter_n);

Example:-


function Employee(first_name, last_name){
	
	this.full_name="Welcome "+first_name+" "+last_name;

}

// Now, create the Object

var emp= new Employee("John","Mathew");
console.log(emp.full_name);
Output:- Welcome John Mathew

You can create multiple objects based on your requirements.


var emp= new Employee("Rom","Taylor");
console.log(emp.full_name);
Output:- Welcome Rom Taylor

Adding property into the constructor function object


function Employee(first_name, last_name){
     
this.firstName=first_name;

this.lastName=last_name;

this.fullName= function(){
	
	return this.firstName+" "+this.lastName;
}

}

Suppose, you have to add new property department in the constructor function employee.


var emp = new Employee("John","Mathew");
emp.department="Sales";
console.log(emp.department)
Output:- Sales

Now, you create another object and call the department property then it will show undefined.


var emp2 = new Employee("Rom","Taylor");
console.log(emp2.department)
Output:- undefined

Note:- If you add property after created the object then it will work for same object not other object.

Javascript Prototype

prototype is a most important part of the JavaScript. If you create the object then property and method of this object always inherit from the prototype.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1);

Output:-


Student {firstName: "John", lastName: "Mathew", age: 35}
age: 35
firstName: "John"
lastName: "Mathew"
__proto__:
constructor: ƒ Student(first_name, last_name, age)
__proto__:
constructor: ƒ Object()
hasOwnProperty: ƒ hasOwnProperty()
isPrototypeOf: ƒ isPrototypeOf()
propertyIsEnumerable: ƒ propertyIsEnumerable()
toLocaleString: ƒ toLocaleString()
toString: ƒ toString()
valueOf: ƒ valueOf()
__defineGetter__: ƒ __defineGetter__()
__defineSetter__: ƒ __defineSetter__()
__lookupGetter__: ƒ __lookupGetter__()
__lookupSetter__: ƒ __lookupSetter__()
get __proto__: ƒ __proto__()
set __proto__: ƒ __proto__()

Why the need of the prototype in the property and methods?

Prototype is used to add property or method after created the constructor function.

Suppose you have Student constructor function which have 3 parameters first_name, last_name and age.


function Student(first_name, last_name, age){
     
this.firstName=first_name;

this.lastName=last_name;

this.age=age;

}

Add Property after created the constructor function

Now, you want to add new property class after created the constructor function.

Student.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- undefined

Now, you will use prototype to add into property after created the constructor function.

Example:-


Student.prototype.class="MCA";
var stu1 = new Student("John","Mathew",35);
console.log(stu1.class);
Output:- MCA

Add method after created the constructor function


Student.address= function(){
	
 return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address);
Uncaught TypeError: stu1.address is not a function

Now, you will add prototype in the method after created the constructor function


Student.prototype.address= function(){
	
	return 'Laxmi Nagar, New Delhi';

}

var stu1 = new Student("John","Mathew",35);
console.log(stu1.address());
Output:- Laxmi Nagar, New Delhi

What is JavaScript

Javascript is a most popular Programming language in the world.
In the starting, JavaScript was used for web browser to build the attractive web pages.
After Node came it is used for Web and mobile App, Real time Networking Application like real chat, etc.

Where JavaScript run?

1) Javascript code write into the script tag.

Syntax:-


<script>
// write code

</script>

Write the code into the script tag


<script>
document.write("Hello JavaScript");
</script>

Try it Yourself

It will show on the browser page.

Output:- Hello JavaScript

2) You can javascript run on the browser console.


> console.log("Hello JavaScript");
Output:- Hello JavaScript

Add two numeric value


<script>
document.write(2+2);
</script>

Try it Yourself

Output:- 4

Add two string


<script>
document.write("Welcome"+" John");
</script>

Try it Yourself

Output:- Welcome John

Javascript setImmediate() method

It will execute code at the end of the current event loop cycle. setImmediate() will execute after any I/O operations in the current event loop and before any timers scheduled (setInterval(), setTimeout()) for the next event loop.


console.log("Hello");
            let data=()=>{
                console.log("Hi");
            }

          
            setTimeout(() => {
                console.log('set Timeout Call');
            }, 0);
           

            setImmediate(()=>{

                console.log("set Immediate Call")

            })

            process.nextTick(()=>{

                console.log('next Tick call');

            })
            data();
            console.log("Bye");
Output:- Hello
Bye
Hi
next Tick call
set Immediate Call
set Timeout Call

Javascript setTimeout() method

setTimeout() method is called when delay time has finished. it is not executed immediately. If there are two function setImmediate and setTimeout are called in the current event loop cycle then first call setImmediate after that setTimeout.


setTimeout(() => {
                console.log('set Timeout Call');
            }, 0);
            
 
  setImmediate(()=>{
 
  console.log("set Immediate Call")
 
 })
Output:- set Immediate Call
set Timeout Call

The clearTimeout() method in javascript clears the timeout which has been set by setTimeout() function.

Javascript setInterval() method

setInterval() method is used to repeat the execution of your code block at specified intervals.
setInterval(callback, milisecond);
basically two parameters need to run this function.


var number=1;
function incrementNumber(number){
	
	console.log(number)
}

setInterval(()=>{
	incrementNumber(number++);
},1000)
Output:- 1
2
3

Note:-It will run continuously while you close this.

What is Generators

Generators are a function that is used for lazy execution. it is used to execute suspended and resumed at a later point.

Generators have two methods

Yield method – This method is called in a function to halt the execution of the function at the specific line where the yield method is called.

Next method – This method is called from the main application to resume the execution of a function that has a yield method. The execution of the function will continue until the next yield method or till the end of the method.


function* addNumber(x) {
   yield x + 1;   //value of x is 6 but halted program
   var y = 2;
   return x + y;
}
var gen = addNumber(5);
console.log(gen.next().value);  //6
console.log(gen.next().value);  //7

Difference between var and let variable

Es6 (ECMAScript 6) introduced two data types let and const for the variable declaration. var data type is a part of Es5(ECMAScript 5).
var is used for function scoped and let is used for block scoped.


example:- for(let i=0;i<10;i++){
console.log(i);
}
console.log(i); 
Output:- 0,1,2,....,9
Output:- throws an error as "i is not defined" because i is not visible

Difference between ES5 and ES6

1) ES5:- It is the 5th edition of Echma Script.
ES6:- It is the 6th edition of Echma Script.

2) Datatypes:- ES5:- It is used number,string,null,undefined,boolean
ES6:- It is added aditional feature “symbol” data type

3) Variable declaration:- ES5:- it is used only var keyword.
ES6:- it is introduced new keywords let and const.

4) Arrow function:- ES6:- it is introduced Arrow function so there is no need function write.

5) loop:- ES5:- It has for loop.
ES6:- It is introduced new loop “for of”

Difference between for in and for of

for in:- this is used to get key and value from the Object.


let employee = {
   "name": "John",
   "salary": 100000,
   "department": "Lead Developer"
}

for(const key in employee) {
   console.log( employee[key]);
}
Output:- John
100000
Lead Developer

for of:- this is used to get the key and value from the Array.


let designation = ["Developer","Sr. Developer","Lead Developer","Team Leader","Project Manager"];
for(const item of designation) {
   console.log(item);
}
Output:-
Developer
Sr. Developer
Lead Developer
Team Leader
Project Manager