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 three method to empty the array list
Method1:- arrayList defined empty array.
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.

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

Method3:-
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 []

How to reverse string in Javascript?

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

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

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

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

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

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


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