To know the type of a JavaScript variable, we can use the typeof operator.
1. Primitive types
String - It represents a series of characters and is written with quotes. A string can be represented using a single or a double quote.
Example :
xxxxxxxxxx21var str = "Vivek Singh Bisht"; //using double quotes2var str2 = 'John Doe'; //using single quotesExample :
xxxxxxxxxx21var x = 3; //without decimal2var y = 3.6; //with decimalExample :
xxxxxxxxxx11var bigInteger = 234567890123456789012345678901234567890;Example :
xxxxxxxxxx51var a = 2;2var b = 3;3var c = 2;4(a == b) // returns false5(a == c) //returns trueExample :
xxxxxxxxxx21var x; // value of x is undefined2var y = undefined; // we can also set the value of a variable as undefinedExample :
xxxxxxxxxx11var z = null;Example :
xxxxxxxxxx11var symbol1 = Symbol('symbol');xxxxxxxxxx71typeof "John Doe" // Returns "string"2typeof 3.14 // Returns "number"3typeof true // Returns "boolean"4typeof 234567890123456789012345678901234567890n // Returns bigint5typeof undefined // Returns "undefined"6typeof null // Returns "object" (kind of a bug in JavaScript)7typeof Symbol('symbol') // Returns Symbol2. Non-primitive types
xxxxxxxxxx131// Collection of data in key-value pairs23var obj1 = {4 x: 43,5 y: "Hello world!",6 z: function(){7 return this.x;8 }9}10 11// Collection of data as an ordered list12 13var array1 = [5, "Hello", true, 4.1]; Note- It is important to remember that any data type that is not a primitive data type, is of Object type in javascript.
Hoisting is the default behaviour of javascript where all the variable and function declarations are moved on top.

This means that irrespective of where the variables and functions are declared, they are moved on top of the scope. The scope can be both local and global.
Example 1:
xxxxxxxxxx31hoistedVariable = 3;2console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized 3var hoistedVariable;Example 2:
xxxxxxxxxx51hoistedFunction(); // Outputs " Hello world! " even when the function is declared after calling23function hoistedFunction(){ 4 console.log(" Hello world! ");5} Example 3:
xxxxxxxxxx61// Hoisting takes place in the local scope as well2function doSomething(){3 x = 33;4 console.log(x);5 var x;6} doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope
Note - Variable initializations are not hoisted, only variable declarations are hoisted:
xxxxxxxxxx31var x;2console.log(x); // Outputs "undefined" since the initialization of "x" is not hoisted3x = 23;Note - To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:
xxxxxxxxxx31"use strict";2x = 23; // Gives an error since 'x' is not declared3var x;The debugger for the browser must be activated in order to debug the code. Built-in debuggers may be switched on and off, requiring the user to report faults. The remaining section of the code should stop execution before moving on to the next line while debugging.
Both are comparison operators. The difference between both the operators is that “” is used to compare values whereas, “ = “ is used to compare both values and types.
Example:
xxxxxxxxxx41var x = 2;2var y = "2";3(x == y) // Returns true since the value of both x and y is the same4(x === y) // Returns false since the typeof x is "number" and typeof y is "string"Some differences are
Implicit type coercion in javascript is the automatic conversion of value from one data type to another. It takes place when the operands of an expression are of different data types.
String coercion takes place while using the ‘ + ‘ operator. When a number is added to a string, the number type is always converted to the string type.
Example 1:
xxxxxxxxxx31var x = 3;2var y = "3";3x + y // Returns "33" Example 2:
xxxxxxxxxx31var x = 24;2var y = "Hello";3x + y // Returns "24Hello"; Note - ‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:
xxxxxxxxxx31var name = "Vivek";2var surname = " Bisht";3name + surname // Returns "Vivek Bisht" Let’s understand both the examples where we have added a number to a string,
When JavaScript sees that the operands of the expression x + y are of different types ( one being a number type and the other being a string type ), it converts the number type to the string type and then performs the operation. Since after conversion, both the variables are of string type, the ‘ + ‘ operator outputs the concatenated string “33” in the first example and “24Hello” in the second example.
Note - Type coercion also takes place when using the ‘ - ‘ operator, but the difference while using ‘ - ‘ operator is that, a string is converted to a number and then subtraction takes place.
xxxxxxxxxx31var x = 3;2Var y = "3";3x - y //Returns 0 since the variable y (string type) is converted to a number typeBoolean coercion takes place when using logical operators, ternary operators, if statements, and loop checks. To understand boolean coercion in if statements and operators, we need to understand truthy and falsy values.
Truthy values are those which will be converted (coerced) to true. Falsy values are those which will be converted to false.
All values except false, 0, 0n, -0, “”, null, undefined, and NaN are truthy values.
If statements:
Example:
xxxxxxxxxx61var x = 0;2var y = 23;3 4if(x) { console.log(x) } // The code inside this block will not run since the value of x is 0(Falsy) 5 6if(y) { console.log(y) } // The code inside this block will run since the value of y is 23 (Truthy)Logical operators in javascript, unlike operators in other programming languages, do not return true or false. They always return one of the operands.
OR ( | | ) operator - If the first value is truthy, then the first value is returned. Otherwise, always the second value gets returned.
AND ( && ) operator - If both the values are truthy, always the second value is returned. If the first value is falsy then the first value is returned or if the second value is falsy then the second value is returned.
Example:
xxxxxxxxxx191var x = 220;2var y = "Hello";3var z = undefined;4 5x | | y // Returns 220 since the first value is truthy6 7x | | z // Returns 220 since the first value is truthy8 9x && y // Returns "Hello" since both the values are truthy10 11y && z // Returns undefined since the second value is falsy12 13if( x && y ){ 14 console.log("Code runs" ); // This block runs because x && y returns "Hello" (Truthy)15} 16 17if( x || z ){18 console.log("Code runs"); // This block runs because x || y returns 220(Truthy)19}Equality coercion takes place when using ‘ == ‘ operator. As we have stated before
The ‘ == ‘ operator compares values and not types.
While the above statement is a simple way to explain == operator, it’s not completely true
The reality is that while using the ‘==’ operator, coercion takes place.
The ‘==’ operator, converts both the operands to the same type and then compares them.
Example:
xxxxxxxxxx31var a = 12;2var b = "12";3a == b // Returns true because both 'a' and 'b' are converted to the same type and then compared. Hence the operands are equal.Coercion does not take place when using the ‘=’ operator. Both operands are not converted to the same type in the case of ‘=’ operator.
Example:
xxxxxxxxxx41var a = 226;2var b = "226";34a === b // Returns false because coercion does not take place and the operands are of different types. Hence they are not equal. JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to a statically typed language, where the type of a variable is checked during compile-time.
Since javascript is a loosely(dynamically) typed language, variables in JS are not associated with any type. A variable can hold the value of any data type.
For example, a variable that is assigned a number type can be converted to a string type:
xxxxxxxxxx21var a = 23;2var a = "Hello World!";NaN property represents the “Not-a-Number” value. It indicates a value that is not a legal number.
typeof of NaN will return a Number.
To check if a value is NaN, we use the isNaN() function,
Note- isNaN() function converts the given value to a Number type, and then equates to NaN.
xxxxxxxxxx61isNaN("Hello") // Returns true2isNaN(345) // Returns false3isNaN('1') // Returns false, since '1' is converted to Number type which results in 0 ( a number) 4isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)5isNaN(false) // Returns false6isNaN(undefined) // Returns trueIn JavaScript, primitive data types are passed by value and non-primitive data types are passed by reference.
For understanding passed by value and passed by reference, we need to understand what happens when we create a variable and assign a value to it,
xxxxxxxxxx11var x = 2;In the above example, we created a variable x and assigned it a value of “2”. In the background, the “=” (assign operator) allocates some space in the memory, stores the value “2” and returns the location of the allocated memory space. Therefore, the variable x in the above code points to the location of the memory space instead of pointing to the value 2 directly.
Assign operator behaves differently when dealing with primitive and non-primitive data types,
Assign operator dealing with primitive types:

xxxxxxxxxx21var y = 234;2var z = y;In the above example, the assign operator knows that the value assigned to y is a primitive type (number type in this case), so when the second line code executes, where the value of y is assigned to z, the assign operator takes the value of y (234) and allocates a new space in the memory and returns the address. Therefore, variable z is not pointing to the location of variable y, instead, it is pointing to a new location in the memory.
xxxxxxxxxx91var y = #8454; // y pointing to address of the value 23423var z = y; 4 5var z = #5411; // z pointing to a completely new address of the value 2346 7// Changing the value of y8y = 23;9console.log(z); // Returns 234, since z points to a new address in the memory so changes in y will not effect zFrom the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created.
Assign operator dealing with non-primitive types:

xxxxxxxxxx21var obj = { name: "Vivek", surname: "Bisht" };2var obj2 = obj;In the above example, the assign operator directly passes the location of the variable obj to the variable obj2. In other words, the reference of the variable obj is passed to the variable obj2.
xxxxxxxxxx111var obj = #8711; // obj pointing to address of { name: "Vivek", surname: "Bisht" }2var obj2 = obj;3 4var obj2 = #8711; // obj2 pointing to the same address 56// changing the value of obj17 8obj.name = "Akki";9console.log(obj2);10 11// Returns {name:"Akki", surname:"Bisht"} since both the variables are pointing to the same address.From the above example, we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference).
Therefore, non-primitive data types are always passed by reference.
An Immediately Invoked Function ( known as IIFE and pronounced as IIFY) is a function that runs as soon as it is defined.
Syntax of IIFE :
xxxxxxxxxx31(function(){ 2 // Do something;3})();To understand IIFE, we need to understand the two sets of parentheses that are added while creating an IIFE :
The first set of parenthesis:
xxxxxxxxxx31(function (){2 //Do something;3})While executing javascript code, whenever the compiler sees the word “function”, it assumes that we are declaring a function in the code. Therefore, if we do not use the first set of parentheses, the compiler throws an error because it thinks we are declaring a function, and by the syntax of declaring a function, a function should always have a name.
xxxxxxxxxx41function() {2 //Do something;3}4// Compiler gives an error since the syntax of declaring a function is wrong in the code above.To remove this error, we add the first set of parenthesis that tells the compiler that the function is not a function declaration, instead, it’s a function expression.
The second set of parenthesis:
xxxxxxxxxx31(function (){2 //Do something;3})();From the definition of an IIFE, we know that our code should run as soon as it is defined. A function runs only when it is invoked. If we do not invoke the function, the function declaration is returned:
xxxxxxxxxx51(function (){2 // Do something;3})45// Returns the function declarationTherefore to invoke the function, we use the second set of parenthesis.
In ECMAScript 5, a new feature called JavaScript Strict Mode allows you to write a code or a function in a "strict" operational environment. In most cases, this language is 'not particularly severe' when it comes to throwing errors. In 'Strict mode,' however, all forms of errors, including silent errors, will be thrown. As a result, debugging becomes a lot simpler. Thus programmer's chances of making an error are lowered.
Characteristics of strict mode in javascript
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions.
Higher-order functions are a result of functions being first-class citizens in javascript.
Examples of higher-order functions:
xxxxxxxxxx121function higherOrder(fn) {2 fn();3}4 5higherOrder(function() { console.log("Hello world") }); 6function higherOrder2() {7 return function() {8 return "Do something";9 }10} 11var x = higherOrder2();12x() // Returns "Do something"The “this” keyword refers to the object that the function is a property of.
*The value of the “this” keyword will always depend on the object that is invoking the function.*
Confused? Let’s understand the above statements by examples:
xxxxxxxxxx51function doSomething() {2 console.log(this);3}4 5doSomething();What do you think the output of the above code will be?
Note - Observe the line where we are invoking the function.
Check the definition again:
The “this” keyword refers to the object that the function is a property of.
In the above code, the function is a property of which object?
Since the function is invoked in the global context, the function is a property of the global object.
Therefore, the output of the above code will be the global object. Since we ran the above code inside the browser, the global object is the window object.
Example 2:
xxxxxxxxxx81var obj = {2 name: "vivek",3 getName: function(){4 console.log(this.name);5 }6}7 8obj.getName();In the above code, at the time of invocation, the getName function is a property of the object obj , therefore, this keyword will refer to the object obj, and hence the output will be “vivek”.
Example 3:
xxxxxxxxxx121 var obj = {2 name: "vivek",3 getName: function(){4 console.log(this.name);5 }6 7}8 9var getName = obj.getName;10 11var obj2 = {name:"akshay", getName };12obj2.getName();Can you guess the output here?
The output will be “akshay”.
Although the getName function is declared inside the object obj, at the time of invocation, getName() is a property of obj2, therefore the “this” keyword will refer to obj2.
The silly way to understand the “this” keyword is, whenever the function is invoked, check the object before the dot. The value of this . keyword will always be the object before the dot.
If there is no object before the dot-like in example1, the value of this keyword will be the global object.
Example 4:
xxxxxxxxxx101var obj1 = {2 address : "Mumbai,India",3 getAddress: function(){4 console.log(this.address); 5 }6}7 8var getAddress = obj1.getAddress;9var obj2 = {name:"akshay"};10obj2.getAddress(); Can you guess the output?
The output will be an error.
Although in the code above, this keyword refers to the object obj2, obj2 does not have the property “address”‘, hence the getAddress function throws an error.
Without being requested, a self-invoking expression is automatically invoked (initiated). If a function expression is followed by (), it will execute automatically. A function declaration cannot be invoked by itself.
Normally, we declare a function and call it, however, anonymous functions may be used to run a function automatically when it is described and will not be called again. And there is no name for these kinds of functions.
1. call():
xxxxxxxxxx91function sayHello(){2 return "Hello " + this.name;3}4 5var obj = {name: "Sandy"};6 7sayHello.call(obj);8 9// Returns "Hello Sandy" xxxxxxxxxx91var person = {2 age: 23,3 getAge: function(){4 return this.age;5 }6} 7var person2 = {age: 54};8person.getAge.call(person2); 9// Returns 54 xxxxxxxxxx61function saySomething(message){2 return this.name + " is " + message;3} 4var person4 = {name: "John"}; 5saySomething.call(person4, "awesome");6// Returns "John is awesome" apply()
The apply method is similar to the call() method. The only difference is that,
call() method takes arguments separately whereas, apply() method takes arguments as an array.
xxxxxxxxxx51function saySomething(message){2 return this.name + " is " + message;3} 4var person4 = {name: "John"};5saySomething.apply(person4, ["awesome"]);2. bind():
xxxxxxxxxx151var bikeDetails = {2 displayDetails: function(registrationNumber,brandName){3 return this.name+ " , "+ "bike details: "+ registrationNumber + " , " + brandName;4 }5}6 7var person1 = {name: "Vivek"};8 9var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, "TS0122", "Bullet");10 11// Binds the displayDetails function to the person1 object12 13 14detailsOfPerson1();15//Returns Vivek, bike details: TS0122, BulletCurrying is an advanced technique to transform a function of arguments n, to n functions of one or fewer arguments.
Example of a curried function:
xxxxxxxxxx71function add (a) {2 return function(b){3 return a + b;4 }5}67add(3)(4) For Example, if we have a function f(a,b), then the function after currying, will be transformed to f(a)(b).
By using the currying technique, we do not change the functionality of a function, we just change the way it is invoked.
Let’s see currying in action:
xxxxxxxxxx171function multiply(a,b){2 return a*b;3}45function currying(fn){6 return function(a){7 return function(b){8 return fn(a,b);9 }10 }11}1213var curriedMultiply = currying(multiply);1415multiply(4, 3); // Returns 121617curriedMultiply(4)(3); // Also returns 12As one can see in the code above, we have transformed the function multiply(a,b) to a function curriedMultiply , which takes in one parameter at a time.
External JavaScript is the JavaScript Code (script) written in a separate file with the extension.js, and then we link that file inside the
or element of the HTML file where the code is to be placed.Some advantages of external javascript are
Scope in JS determines the accessibility of variables and functions at various parts of one’s code.
In general terms, the scope will let us know at a given part of code, what are variables and functions we can or cannot access.
There are three types of scopes in JS:
Global Scope: Variables or functions declared in the global namespace have global scope, which means all the variables and functions having global scope can be accessed from anywhere inside the code.
xxxxxxxxxx91var globalVariable = "Hello world";23function sendMessage(){4 return globalVariable; // can access globalVariable since it's written in global space5}6function sendMessage2(){7 return sendMessage(); // Can access sendMessage function since it's written in global space8}9sendMessage2(); // Returns “Hello world”Function Scope: Any variables or functions declared inside a function have local/function scope, which means that all the variables and functions declared inside a function, can be accessed from within the function and not outside of it.
xxxxxxxxxx101function awesomeFunction(){2 var a = 2;34 var multiplyBy2 = function(){5 console.log(a*2); // Can access variable "a" since a and multiplyBy2 both are written inside the same function6 }7}8console.log(a); // Throws reference error since a is written in local scope and cannot be accessed outside910multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scopeBlock Scope: Block scope is related to the variables declared using let and const. Variables declared with var do not have block scope. Block scope tells us that any variable declared inside a block { }, can be accessed only inside that block and cannot be accessed outside of it.
xxxxxxxxxx111{2 let x = 45;3}45console.log(x); // Gives reference error since x cannot be accessed outside of the block67for(let i=0; i<2; i++){8 // do something9}1011console.log(i); // Gives reference error since i cannot be accessed outside of the for loop blockScope Chain: JavaScript engine also uses Scope to find variables. Let’s understand that using an example:
xxxxxxxxxx161var y = 24;23function favFunction(){4 var x = 667;5 var anotherFavFunction = function(){6 console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside favFunction, outputs 6677 }89 var yetAnotherFavFunction = function(){10 console.log(y); // Does not find y inside yetAnotherFavFunction, so looks for variable inside favFunction and does not find it, so looks for variable in global scope, finds it and outputs 2411 }1213 anotherFavFunction();14 yetAnotherFavFunction();15}16favFunction();As you can see in the code above, if the javascript engine does not find the variable in local scope, it tries to check for the variable in the outer scope. If the variable does not exist in the outer scope, it tries to find the variable in the global scope.
If the variable is not found in the global space as well, a reference error is thrown.
Closures are an ability of a function to remember the variables and functions that are declared in its outer scope.
xxxxxxxxxx101var Person = function(pName){2 var name = pName;34 this.getName = function(){5 return name;6 }7}89var person = new Person("Neelesh");10console.log(person.getName());Let’s understand closures by example:
xxxxxxxxxx121function randomFunc(){2 var obj1 = {name:"Vivian", age:45};34 return function(){5 console.log(obj1.name + " is "+ "awesome"); // Has access to obj1 even when the randomFunc function is executed67 }8}910var initialiseClosure = randomFunc(); // Returns a function1112initialiseClosure(); Let’s understand the code above,
The function randomFunc() gets executed and returns a function when we assign it to a variable:
xxxxxxxxxx11var initialiseClosure = randomFunc();The returned function is then executed when we invoke initialiseClosure:
xxxxxxxxxx11initialiseClosure(); The line of code above outputs “Vivian is awesome” and this is possible because of closure.
xxxxxxxxxx11console.log(obj1.name + " is "+ "awesome");When the function randomFunc() runs, it seems that the returning function is using the variable obj1 inside it:
Therefore randomFunc(), instead of destroying the value of obj1 after execution, saves the value in the memory for further reference. This is the reason why the returning function is able to use the variable declared in the outer scope even after the function is already executed.
This ability of a function to store a variable for further reference even after it is executed is called Closure.
There are many advantages of javascript. Some of them are
All javascript objects inherit properties from a prototype. For example,
Let’s see prototypes help us use methods and properties:

xxxxxxxxxx41var arr = [];2arr.push(2);34console.log(arr); // Outputs [2]In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.
The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.
The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.
Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on.
A callback is a function that will be executed after another function gets executed. In javascript, functions are treated as first-class citizens, they can be used as an argument of another function, can be returned by another function, and can be used as a property of an object.
Functions that are used as an argument to another function are called callback functions. Example:
xxxxxxxxxx161function divideByHalf(sum){2 console.log(Math.floor(sum / 2));3}45function multiplyBy2(sum){6 console.log(sum * 2);7}89function operationOnSum(num1,num2,operation){10 var sum = num1 + num2;11 operation(sum);12}1314operationOnSum(3, 3, divideByHalf); // Outputs 31516operationOnSum(5, 5, multiplyBy2); // Outputs 20There are two types of errors in javascript.
Memoization is a form of caching where the return value of a function is cached based on its parameters. If the parameter of that function is not changed, the cached version of the function is returned. Let’s understand memoization, by converting a simple function to a memoized function:
Note- Memoization is used for expensive function calls but in the following example, we are considering a simple function for understanding the concept of memoization better.
Consider the following function:
xxxxxxxxxx61function addTo256(num){2 return num + 256;3}4addTo256(20); // Returns 2765addTo256(40); // Returns 2966addTo256(20); // Returns 276In the code above, we have written a function that adds the parameter to 256 and returns it.
When we are calling the function addTo256 again with the same parameter (“20” in the case above), we are computing the result again for the same parameter.
Computing the result with the same parameter, again and again, is not a big deal in the above case, but imagine if the function does some heavy-duty work, then, computing the result again and again with the same parameter will lead to wastage of time.
This is where memoization comes in, by using memoization we can store(cache) the computed results based on the parameters. If the same parameter is used again while invoking the function, instead of computing the result, we directly return the stored (cached) value.
Let’s convert the above function addTo256, to a memoized function:
xxxxxxxxxx181function memoizedAddTo256(){2 var cache = {};34 return function(num){5 if(num in cache){6 console.log("cached value");7 return cache[num]8 }9 else{10 cache[num] = num + 256;11 return cache[num];12 }13 }14}15var memoizedFunc = memoizedAddTo256();1617memoizedFunc(20); // Normal return18memoizedFunc(20); // Cached returnIn the code above, if we run the memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.
Note- Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.
Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.
xxxxxxxxxx111function add(number) {2 if (number <= 0) {3 return 0;4 } else {5 return number + add(number - 1);6 }7}8add(3) => 3 + add(2)9 3 + 2 + add(1)10 3 + 2 + 1 + add(0)11 3 + 2 + 1 + 0 = 6 Example of a recursive function:
The following function calculates the sum of all the elements in an array by using recursion:
xxxxxxxxxx91function computeSum(arr){2 if(arr.length === 1){3 return arr[0];4 }5 else{6 return arr.pop() + computeSum(arr);7 }8}9computeSum([7, 8, 9, 99]); // Returns 123Constructor functions are used to create objects in javascript.
When do we use constructor functions?
If we want to create multiple objects having similar properties and methods, constructor functions are used.
Note- The name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.
Example:
xxxxxxxxxx121function Person(name,age,gender){2 this.name = name;3 this.age = age;4 this.gender = gender;5}678var person1 = new Person("Vivek", 76, "male");9console.log(person1);1011var person2 = new Person("Courtney", 34, "female");12console.log(person2);In the code above, we have created a constructor function named Person. Whenever we want to create a new object of the type Person, We need to create it using the new keyword:
xxxxxxxxxx11var person3 = new Person("Lilly", 17, "female");The above line of code will create a new object of the type Person. Constructor functions allow us to group similar objects.

The charAt() function of the JavaScript string finds a char element at the supplied index. The index number begins at 0 and continues up to n-1, Here n is the string length. The index value must be positive, higher than, or the same as the string length.
Browser Object Model is known as BOM. It allows users to interact with the browser. A browser's initial object is a window. As a result, you may call all of the window's functions directly or by referencing the window. The document, history, screen, navigator, location, and other attributes are available in the window object.
Client-side JavaScript is made up of two parts, a fundamental language and predefined objects for performing JavaScript in a browser. JavaScript for the client is automatically included in the HTML pages. At runtime, the browser understands this script.

Server-side JavaScript, involves the execution of JavaScript code on a server in response to client requests. It handles these requests and delivers the relevant response to the client, which may include client-side JavaScript for subsequent execution within the browser.
Arrow functions were introduced in the ES6 version of javascript. They provide us with a new and shorter syntax for declaring functions. Arrow functions can only be used as a function expression.
Let’s compare the normal function declaration and the arrow function declaration in detail:
xxxxxxxxxx71// Traditional Function Expression2var add = function(a,b){3 return a + b;4}56// Arrow Function Expression7var arrowAdd = (a,b) => a + b;Arrow functions are declared without the function keyword. If there is only one returning expression then we don’t need to use the return keyword as well in an arrow function as shown in the example above. Also, for functions having just one line of code, curly braces { } can be omitted.
xxxxxxxxxx61// Traditional function expression2var multiplyBy2 = function(num){3 return num * 2;4}5// Arrow function expression6var arrowMultiplyBy2 = num => num * 2;If the function takes in only one argument, then the parenthesis () around the parameter can be omitted as shown in the code above.
xxxxxxxxxx131var obj1 = {2 valueOfThis: function(){3 return this;4 }5}6var obj2 = {7 valueOfThis: ()=>{8 return this;9 }10}1112obj1.valueOfThis(); // Will return the object obj113obj2.valueOfThis(); // Will return window/global objectThe biggest difference between the traditional function expression and the arrow function is the handling of this keyword. By general definition, this keyword always refers to the object that is calling the function. As you can see in the code above, obj1.valueOfThis() returns obj1 since this keyword refers to the object calling the function.
In the arrow functions, there is no binding of this keyword. This keyword inside an arrow function does not refer to the object calling it. It rather inherits its value from the parent scope which is the window object in this case. Therefore, in the code above, obj2.valueOfThis() returns the window object.
The Prototype Pattern produces different objects, but instead of returning uninitialized objects, it produces objects that have values replicated from a template – or sample – object. Also known as the Properties pattern, the Prototype pattern is used to create prototypes.
The introduction of business objects with parameters that match the database's default settings is a good example of where the Prototype pattern comes in handy. The default settings for a newly generated business object are stored in the prototype object.
The Prototype pattern is hardly used in traditional languages, however, it is used in the development of new objects and templates in JavaScript, which is a prototypal language.
Before the ES6 version of javascript, only the keyword var was used to declare variables. With the ES6 Version, keywords let and const were introduced to declare variables.
| keyword | const | let | var |
|---|---|---|---|
| global scope | no | no | yes |
| function scope | yes | yes | yes |
| block scope | yes | yes | no |
| can be reassigned | no | yes | yes |
Let’s understand the differences with examples:
xxxxxxxxxx141var variable1 = 23;23let variable2 = 89;45function catchValues(){6 console.log(variable1);7 console.log(variable2);89// Both the variables can be accessed anywhere since they are declared in the global scope10}1112window.variable1; // Returns the value 231314window.variable2; // Returns undefinedvar vs let in functional scope
xxxxxxxxxx71function varVsLetFunction(){2 let awesomeCar1 = "Audi";3 var awesomeCar2 = "Mercedes";4}56console.log(awesomeCar1); // Throws an error7console.log(awesomeCar2); // Throws an errorVariables are declared in a functional/local scope using var and let keywords behave exactly the same, meaning, they cannot be accessed from outside of the scope.
xxxxxxxxxx231{2 var variable3 = [1, 2, 3, 4];3}45console.log(variable3); // Outputs [1,2,3,4]67{8 let variable4 = [6, 55, -1, 2];9}1011console.log(variable4); // Throws error1213for(let i = 0; i < 2; i++){14 //Do something15}1617console.log(i); // Throws error1819for(var j = 0; j < 2; i++){20 // Do something21}2223console.log(j) // Outputs 2 Const keyword
xxxxxxxxxx91const x = {name:"Vivek"};23x = {address: "India"}; // Throws an error45x.name = "Nikhil"; // No error is thrown67const y = 23;89y = 44; // Throws an errorIn the code above, although we can change the value of a property inside the variable declared with const keyword, we cannot completely reassign the variable itself.
Both rest parameter and spread operator were introduced in the ES6 version of javascript.
Rest parameter ( … ):
xxxxxxxxxx181function extractingArgs(args){2 return args[1];3}45// extractingArgs(8,9,1); // Returns 967function addAllArgs(args){8 let sumOfArgs = 0;9 let i = 0;10 while(i < args.length){11 sumOfArgs += args[i];12 i++;13 }14 return sumOfArgs;15}1617addAllArgs(6, 5, 7, 99); // Returns 11718addAllArgs(1, 3, 4); // Returns 8**Note- Rest parameter should always be used at the last parameter of a function:
xxxxxxxxxx91// Incorrect way to use rest parameter2function randomFunc(a,args,c){3//Do something4}56// Correct way to use rest parameter7function randomFunc2(a,b,args){8//Do something9}xxxxxxxxxx241function addFourNumbers(num1,num2,num3,num4){2 return num1 + num2 + num3 + num4;3}45let fourNumbers = [5, 6, 7, 8];678addFourNumbers(fourNumbers);9// Spreads [5,6,7,8] as 5,6,7,81011let array1 = [3, 4, 5, 6];12let clonedArray1 = [array1];13// Spreads the array into 3,4,5,614console.log(clonedArray1); // Outputs [3,4,5,6]151617let obj1 = {x:'Hello', y:'Bye'};18let clonedObj1 = {obj1}; // Spreads and clones obj119console.log(obj1);2021let obj2 = {z:'Yes', a:'No'};22let mergedObj = {obj1, obj2}; // Spreads both the objects and merges it23console.log(mergedObj);24// Outputs {x:'Hello', y:'Bye',z:'Yes',a:'No'};***Note- Key differences between rest parameter and spread operator:
- Rest parameter is used to take a variable number of arguments and turns them into an array while the spread operator takes an array or an object and spreads it
- Rest parameter is used in function declaration whereas the spread operator is used in function calls.
In JavaScript, there are several ways to declare or construct an object.
Promises are used to handle asynchronous operations in javascript.
Before promises, callbacks were used to handle asynchronous operations. But due to the limited functionality of callbacks, using multiple callbacks to handle asynchronous code can lead to unmanageable code.
Promise object has four states -
A promise is created using the Promise constructor which takes in a callback function with two parameters, resolve and reject respectively.

resolve is a function that will be called when the async operation has been successfully completed.
reject is a function that will be called, when the async operation fails or if some error occurs.
Example of a promise:
Promises are used to handle asynchronous operations like server requests, for ease of understanding, we are using an operation to calculate the sum of three elements.
In the function below, we are returning a promise inside a function:
xxxxxxxxxx161function sumOfThreeElements(elements){2 return new Promise((resolve,reject)=>{3 if(elements.length > 3 ){4 reject("Only three elements or less are allowed");5 }6 else{7 let sum = 0;8 let i = 0;9 while(i < elements.length){10 sum += elements[i];11 i++;12 }13 resolve("Sum has been calculated: "+sum);14 }15 })16}In the code above, we are calculating the sum of three elements, if the length of the elements array is more than 3, a promise is rejected, or else the promise is resolved and the sum is returned.
We can consume any promise by attaching then() and catch() methods to the consumer.

then() method is used to access the result when the promise is fulfilled.
catch() method is used to access the result/error when the promise is rejected. In the code below, we are consuming the promise:
xxxxxxxxxx91sumOfThreeElements(4, 5, 6)2.then(result=> console.log(result))3.catch(error=> console.log(error));4// In the code above, the promise is fulfilled so the then() method gets executed56sumOfThreeElements(7, 0, 33, 41)7.then(result => console.log(result))8.catch(error=> console.log(error));9// In the code above, the promise is rejected hence the catch() method gets executedIntroduced in the ES6 version, classes are nothing but syntactic sugars for constructor functions. They provide a new way of declaring constructor functions in javascript. Below are the examples of how classes are declared and used:
xxxxxxxxxx361// Before ES6 version, using constructor functions2function Student(name,rollNumber,grade,section){3 this.name = name;4 this.rollNumber = rollNumber;5 this.grade = grade;6 this.section = section;7}89// Way to add methods to a constructor function10Student.prototype.getDetails = function(){11 return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade: ${this.grade}, Section:${this.section}';12}131415let student1 = new Student("Vivek", 354, "6th", "A");16student1.getDetails();17// Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A1819// ES6 version classes20class Student{21 constructor(name,rollNumber,grade,section){22 this.name = name;23 this.rollNumber = rollNumber;24 this.grade = grade;25 this.section = section;26 }2728 // Methods can be directly added inside the class29 getDetails(){30 return 'Name: ${this.name}, Roll no: ${this.rollNumber}, Grade:${this.grade}, Section:${this.section}';31 }32}3334let student2 = new Student("Garry", 673, "7th", "C");35student2.getDetails();36// Returns Name: Garry, Roll no:673, Grade: 7th, Section:CKey points to remember about classes:
Introduced in the ES6 version, generator functions are a special class of functions.
They can be stopped midway and then continue from where they had stopped.
Generator functions are declared with the function* keyword instead of the normal function keyword:
xxxxxxxxxx31function* genFunc(){2 // Perform operation3}In normal functions, we use the return keyword to return a value and as soon as the return statement gets executed, the function execution stops:
xxxxxxxxxx41function normalFunc(){2 return 22;3 console.log(2); // This line of code does not get executed4}In the case of generator functions, when called, they do not execute the code, instead, they return a generator object. This generator object handles the execution.
xxxxxxxxxx51function* genFunc(){2 yield 3;3 yield 4;4}5genFunc(); // Returns Object [Generator] {}The generator object consists of a method called next(), this method when called, executes the code until the nearest yield statement, and returns the yield value.
For example, if we run the next() method on the above code:
xxxxxxxxxx11genFunc().next(); // Returns {value: 3, done:false}As one can see the next method returns an object consisting of a value and done properties. Value property represents the yielded value. Done property tells us whether the function code is finished or not. (Returns true if finished).
Generator functions are used to return iterators. Let’s see an example where an iterator is returned:
xxxxxxxxxx131function* iteratorFunc() {2 let count = 0;3 for (let i = 0; i < 2; i++) {4 count++;5 yield i;6 }7 return count;8}910let iterator = iteratorFunc();11console.log(iterator.next()); // {value:0,done:false}12console.log(iterator.next()); // {value:1,done:false}13console.log(iterator.next()); // {value:2,done:true}As you can see in the code above, the last line returns done:true, since the code reaches the return statement.
In javascript, a Set is a collection of unique and ordered elements. Just like Set, WeakSet is also a collection of unique and ordered elements with some key differences:
xxxxxxxxxx91const newSet = new Set([4, 5, 6, 7]);2console.log(newSet);// Outputs Set {4,5,6,7}34const newSet2 = new WeakSet([3, 4, 5]); //Throws an error567let obj1 = {message:"Hello world"};8const newSet3 = new WeakSet([obj1]);9console.log(newSet3.has(obj1)); // trueA callback function is a method that is sent as an input to another function (now let us name this other function "thisFunction"), and it is performed inside the thisFunction after the function has completed execution.
JavaScript is a scripting language that is based on events. Instead of waiting for a reply before continuing, JavaScript will continue to run while monitoring for additional events. Callbacks are a technique of ensuring that a particular code does not run until another code has completed its execution.
In javascript, Map is used to store key-value pairs. The key-value pairs can be of both primitive and non-primitive types. WeakMap is similar to Map with key differences:
xxxxxxxxxx91const map1 = new Map();2map1.set('Value', 1);34const map2 = new WeakMap();5map2.set('Value', 2.3); // Throws an error67let obj = {name:"Vivek"};8const map3 = new WeakMap();9map3.set(obj, {age:23});Object destructuring is a new way to extract elements from an object or an array.
xxxxxxxxxx91const classDetails = {2 strength: 78,3 benches: 39,4 blackBoard:15}67const classStrength = classDetails.strength;8const classBenches = classDetails.benches;9const classBlackBoard = classDetails.blackBoard;The same example using object destructuring:
xxxxxxxxxx111const classDetails = {2 strength: 78,3 benches: 39,4 blackBoard:15}67const {strength:classStrength, benches:classBenches,blackBoard:classBlackBoard} = classDetails;89console.log(classStrength); // Outputs 7810console.log(classBenches); // Outputs 3911console.log(classBlackBoard); // Outputs 1As one can see, using object destructuring we have extracted all the elements inside an object in one line of code. If we want our new variable to have the same name as the property of an object we can remove the colon:
xxxxxxxxxx31const {strength:strength} = classDetails;2// The above line of code can be written as:3const {strength} = classDetails;xxxxxxxxxx51const arr = [1, 2, 3, 4];2const first = arr[0];3const second = arr[1];4const third = arr[2];5const fourth = arr[3];The same example using object destructuring:
xxxxxxxxxx61const arr = [1, 2, 3, 4];2const [first,second,third,fourth] = arr;3console.log(first); // Outputs 14console.log(second); // Outputs 25console.log(third); // Outputs 36console.log(fourth); // Outputs 4Programers build objects, which are representations of real-time entities, in traditional OO programming. Classes and objects are the two sorts of abstractions. A class is a generalization of an object, whereas an object is an abstraction of an actual thing. A Vehicle, for example, is a specialization of a Car. As a result, automobiles (class) are descended from vehicles (object).
Classical inheritance differs from prototypal inheritance in that classical inheritance is confined to classes that inherit from those remaining classes, but prototypal inheritance allows any object to be cloned via an object linking method. Despite going into too many specifics, a prototype essentially serves as a template for those other objects, whether they extend the parent object or not.
Temporal Dead Zone is a behaviour that occurs with variables declared using let and const keywords. It is a behaviour where we try to access a variable before it is initialized. Examples of temporal dead zone:
xxxxxxxxxx101x = 23; // Gives reference error23let x;45function anotherRandomFunc(){6 message = "Hello"; // Throws a reference error78 let message;9}10anotherRandomFunc();In the code above, both in the global scope and functional scope, we are trying to access variables that have not been declared yet. This is called the Temporal Dead Zone.
JavaScript design patterns are repeatable approaches for errors that arise sometimes when building JavaScript browser applications. They truly assist us in making our code more stable.
They are divided mainly into 3 categories
The variable's data is always a reference for objects, hence it's always pass by value. As a result, if you supply an object and alter its members inside the method, the changes continue outside of it. It appears to be pass by reference in this case. However, if you modify the values of the object variable, the change will not last, demonstrating that it is indeed passed by value.
A primitive is a data type that isn't composed of other data types. It's only capable of displaying one value at a time. By definition, every primitive is a built-in data type (the compiler must be knowledgeable of them) nevertheless, not all built-in datasets are primitives. In JavaScript, there are 5 different forms of basic data. The following values are available:
The processing of HTML code while the page loads are disabled by nature till the script hasn't halted. Your page will be affected if your network is a bit slow, or if the script is very hefty. When you use Deferred, the script waits for the HTML parser to finish before executing it. This reduces the time it takes for web pages to load, allowing them to appear more quickly.
To support lexical scoping, a JavaScript function object's internal state must include not just the function's code but also a reference to the current scope chain.
xxxxxxxxxx101var scope = "global scope";2function check() 3{4 var scope = "local scope"; 5 function f() 6 { 7 return scope; 8 }9 return f;10}Every executing function, code block, and script as a whole in JavaScript has a related object known as the Lexical Environment. The preceding code line returns the value in scope.