JavaScript Interview Questions and Answers

JavaScript Interview Questions and Answers

Last updated on 05th Oct 2020, Blog, Interview Question

About author

Ranjith (Sr Technical Project Manager )

Highly Expertise in Respective Industry Domain with 10+ Years of Experience Also, He is a Technical Blog Writer for Past 4 Years to Renders A Kind Of Informative Knowledge for JOB Seeker

(5.0) | 15463 Ratings 1932

JavaScript is a lightweight, interpreted programming language with object-oriented capabilities that allows you to build interactivity into otherwise static HTML pages.

The general-purpose core of the language has been embedded in Netscape, Internet Explorer, and other web browsers.

The below questions will give you an idea on how to prepare for a Javascript interview. The number of javascript certified professionals are growing in the IT industry and you need to have all the terminologies, techniques, and best practices on your fingertips in order to be successful in a job interview.

1. What are the different data types present in javascript?

Ans:

To know the type of a JavaScript variable, we can use the typeof operator.

Primitive types

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

  • var str = “Vivek Singh Bisht”; //using double quotes
  •  var str2 = ‘John Doe’; //using single quotes
  1. 2. Number – It represents a number and can be written with or without decimals.

Example :

  • var x = 3; //without decimal
  • var y = 3.6; //with decimal
  1. 3. BigInt – This data type is used to store numbers which are above the limitation of the Number data type. It can store large integers and is represented by adding “n” to an integer literal.

Example :

  • var bigInteger =  234567890123456789012345678901234567890;
  1. 4. Boolean – It represents a logical entity and can have only two values : true or false. Booleans are generally used for conditional testing.

Example :

  • var a = 2;
  • var b =  3;
  • var c =  2;
  • (a == b) // returns false
  • (a == c) //returns true
  1. 5. Undefined – When a variable is declared but not assigned, it has the value of undefined and it’s type is also undefined.

Example :

  • var x; // value of x is undefined
  • var y = undefined; // we can also set the value of a variable as undefined
  1. 6. Null – It represents a non-existent or a invalid value.

Example :

  • var z = null;
  1. 7. Symbol – It is a new data type introduced in the ES6 version of javascript. It is used to store an anonymous and unique value.

Example :

  • var symbol1 = Symbol(‘symbol’);

typeof of primitive types :

  • typeof “John Doe” // Returns “string”
  • typeof 3.14 // Returns “number”
  • typeof true // Returns “boolean”
  • typeof 234567890123456789012345678901234567890n // Returns bigint
  • typeof undefined // Returns “undefined”
  • typeof null // Returns “object” (kind of a bug in JavaScript)
  • typeof Symbol(‘symbol’) // Returns Symbol

Non-primitive types

Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used.

Object – Used to store collection of data.

Example:

  • // Collection of data in key-value pairs
  • var obj1 = {
  •    x:  43,
  •    y:  “Hello world!”,
  •    z: function(){
  •       return this.x;
  •    }
  • }
  • // Collection of data as an ordered list
  • var array1 = [5, “Hello”, true, 4.1];   

It is important to remember that any data type that is not primitive data type, is of Object type in javascript.

2. Explain Hoisting in javascript.

Ans:

Hoisting is a 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:

  • hoistedVariable = 3;
  • console.log(hoistedVariable); // outputs 3 even when the variable is declared after it is initialized
  • var hoistedVariable;

Example 2:

  • hoistedFunction();  // Outputs ” Hello world! ” even when the function is declared after calling
  • function hoistedFunction(){ 
  •   console.log(” Hello world! “);
  • }

Example 3:

  • // Hoisting takes place in the local scope as well
  • function doSomething(){
  •   x = 33;
  •   console.log(x);
  •   var x;
  • }
  • doSomething(); // Outputs 33 since the local variable “x” is hoisted inside the local scope

Variable initializations are not hoisted, only variable declarations are hoisted:

  • var x;
  • console.log(x); // Outputs “undefined” since the initialization of “x” is not hoisted
  • x = 23;
  • To avoid hoisting, you can run javascript in strict mode by using “use strict” on top of the code:
  • “use strict”;
  • x = 23; // Gives an error since ‘x’ is not declared
  • var x; 

3. Difference between “ == “ and “ === “ operators.

Ans:

Both are comparison operators. The difference between both the operators is that,“==” is used to compare values whereas, “ === “ is used to compare both value and types.

Example:

  • var x = 2;
  • var y = “2”;
  • (x == y)  // Returns true since the value of both x and y is the same
  • (x === y) // Returns false since the typeof x is “number” and typeof y is “string”

4. Explain Implicit Type Coercion in javascript.

Ans:

Implicit type coercion in javascript is 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

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:

  • var x = 3;
  • var y = “3”;
  • x + y // Returns “33” 

Example 2:

  • var x = 24;
  • var y = “Hello”;
  • x + y   // Returns “24Hello”;

‘ + ‘ operator when used to add two numbers, outputs a number. The same ‘ + ‘ operator when used to add two strings, outputs the concatenated string:

  • var name = “Vivek”;
  • var surname = ” Bisht”;
  • name + 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.

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.

  • var x = 3;
  • Var y = “3”;
  • x – y    //Returns 0 since the variable y (string type) is converted to a number type

Boolean Coercion

Boolean 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 0, 0n, -0, “”, null, undefined and NaN are truthy values.

If statements:

Example:

  • var x = 0;
  • var y = 23;
  • if(x) {
  • console.log(x)
  • }   // The code inside this block will not run since the value of x is 0(Falsy)  
  • if(y) {
  • console.log(y)
  • }    // The code inside this block will run since the value of y is 23 (Truthy)

Logical operators:

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:

  • var x = 220;
  • var y = “Hello”;
  • var z = undefined;
  • x | | y    // Returns 220 since the first value is truthy
  • x | | z   // Returns undefined 
  • x && y    // Returns “Hello” since both the values are truthy
  • y && z   // Returns undefined since the second value is falsy
  • if( x && y ){ 
  •   console.log(“Code runs” ); // This block runs because x && y returns “Hello” (Truthy)
  • }   
  • if( x || z ){
  •   console.log(“Code does not run”);  // Block does not run because x || y returns undefined(Falsy)
  • }

Equality Coercion

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:

  • var a = 12;
  • var b = “12”;
  • a == 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:

  • var a = 226;
  • var b = “226”;
  • a === b // Returns false because coercion does not take place and the  operands are of different types. Hence they are not equal.

5. Is javascript a statically typed or a dynamically typed language?

Ans:

JavaScript is a dynamically typed language. In a dynamically typed language, the type of a variable is checked during run-time in contrast to 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 which is assigned a number type can be converted to a string type:

  • var a = 23;
  • var a = “Hello World!”;

6. What is NaN property in JavaScript?

Ans:

NaN property represents “Not-a-Number” value. It indicates a value which is not a legal number.

typeof of a NaN will return a Number .

To check if a value is NaN, we use the isNaN() function,

  • isNaN() function converts the given value to a Number type, and then equates to NaN.
  • isNaN(“Hello”)  // Returns true
  • isNaN(345)   // Returns false
  • isNaN(‘1’)  // Returns false, since ‘1’ is converted to Number type which results in 0 ( a number) 
  • isNaN(true) // Returns false, since true converted to Number type results in 1 ( a number)
  • isNaN(false) // Returns false
  • isNaN(undefined) // Returns true

7. Explain passed by value and passed by reference.

Ans:

In 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,

  • var x = 2;

In the above example, we created a variable x and assigned it a value “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:

Pass-By-Value
  • var y = 234;
  • var z = y;

In the above example, 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.

  • var y = #8454; // y pointing to address of the value 234
  • var z = y; 
  • var z = #5411; // z pointing to a completely new address of the value 234
  • // Changing the value of y
  • y = 23;
  • console.log(z);  // Returns 234, since z points to a new address in the memory so changes in y will not effect z

From 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:

Pass-By-Reference
  • var obj = {
  • name: “Vivek”, surname: “Bisht”
  • };
  • var 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.

  • var obj = #8711;    // obj pointing to address of { name: “Vivek”, surname: “Bisht” }
  • var obj2 = obj;
  • var obj2 = #8711;   // obj2 pointing to the same address 
  • // changing the value of obj1
  • obj1.name = “Akki”;
  • console.log(obj2);   // 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 assign operator directly passes the address (reference).

Therefore, non-primitive data types are always passed by reference.

8. What is an Immediately Invoked Function in JavaScript?

Ans:

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 :

  • function(){ 
  •   // Do something;
  • })();

To understand IIFE, we need to understand the two sets of parentheses which are added while creating an IIFE :

First set of parenthesis:

  • (function (){
  •    //Do something;
  • })

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.

  • function() {
  •   //Do something;
  • }

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.

Second set of parenthesis:

  • (function (){
  •   //Do something;
  • })();

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:

  • function (){
  •   // Do something;
  • })   // Returns the function declaration

Therefore to invoke the function, we use the second set of parenthesis. .

9. Explain Higher Order Functions in javascript.

Ans:

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:

  • function higherOrder(fn) {
  •   fn();
  • }
  • higherOrder(function() { console.log(“Hello world”) }); 
  • function higherOrder2() {
  •   return function() {
  •     return “Do something”;
  •   }
  • }
  • var x = higherOrder2();
  • x()   // Returns “Do something”

10. Explain “this” keyword.

Ans:

The “this” keyword refers to the object that the function is a property of.

The value of “this” keyword will always depend on the object that is invoking the function.

Let’s understand the above statements by examples:

  • function doSomething() {
  •   console.log(this);
  • }
  • doSomething();

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.

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:

  • var obj = {
  •     name:  “vivek”,
  •     getName: function(){
  •     console.log(this.name);
  •   }
  • }
  • obj.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:

  • var obj = {
  •     name:  “vivek”,
  •     getName: function(){
  •     console.log(this.name);
  •   }
  • }
  • var getName = obj.getName;
  • var obj2 = {name:”akshay”, getName };
  • obj2.getName();

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

  • var obj1 = {
  •     address : “Mumbai,India”,
  •     getAddress: function(){
  •     console.log(this.address); 
  •   }
  • }
  • var getAddress = obj1.getAddress;
  • var obj2 = {name:”akshay”};
  • obj2.getAddress();    

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.

11. Explain call(), apply() and, bind() methods.

Ans:

call()

It’s a predefined method in javascript. This method invokes a method (function) by specifying the owner object.

Example 1:

  • function sayHello(){
  •   return “Hello ” + this.name;
  • }
  • var obj = {name: “Sandy”};
  • sayHello.call(obj);    // Returns “Hello Sandy”

call() method allows an object to use the method (function) of another object.

Example 2:

  • var person = {
  •   age: 23,
  •   getAge: function(){
  •    return this.age;
  •   }
  • }
  • var person2 = {age:  54};
  • person.getAge.call(person2);   // Returns 54  

call() accepts arguments:

  • function saySomething(message){
  •   return this.name + ” is ” + message;
  • }
  • var person4 = {name:  “John”};
  • saySomething.call(person4, “awesome”);
  • // 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.

  • function saySomething(message){
  •   return this.name + ” is ” + message;
  • }
  • var person4 = {name:  “John”};
  • saySomething.apply(person4, [“awesome”]);

bind()

This method returns a new function, where the value of “this” keyword will be bound to the owner object, which is provided as a parameter.

Example with arguments:

  • var bikeDetails = {
  •     displayDetails: function(registrationNumber,brandName){
  •     return this.name+ ” , “+ “bike details: “+ registrationNumber + ” , ” + brandName;
  •   }
  • }
  • var person1 = {name:  “Vivek”};
  • var detailsOfPerson1 = bikeDetails.displayDetails.bind(person1, “TS0122”, “Bullet”);
  • // Binds the displayDetails function to the person1 object
  • detailsOfPerson1();
  • // Returns Vivek, bike details: TS0452, Thunderbird

12. What is currying in JavaScript?

Ans:

Currying is an advanced technique to transform a function of arguments n, to n functions of one or less arguments.

Example of a curried function:

  • function add (a) {
  •   return function(b){
  •    return a + b;
  •   }
  • }
  • add(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:

  • function multiply(a,b){
  •   return a*b;
  • }
  • function currying(fn){
  •   return function(a){
  •     return function(b){
  •       return fn(a,b);
  •     }
  •   }
  • }
  • var curriedMultiply = currying(multiply);
  • multiply(4, 3); // Returns 12
  • curriedMultiply(4)(3); // Also returns 12

As 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.

Subscribe For Free Demo
[contact-form-7 404 "Not Found"]

13. Explain Scope and Scope Chain in javascript.

Ans:

Scope in JS, determines the accessibility of variables and functions at various parts in one’s code.

In general terms, the scope will let us know at a given part of code, what are the variables and functions that we can or cannot access.

There are three types of scopes in JS:

  • Global Scope
  • Local or Function Scope
  • Block Scope

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

  • var globalVariable = “Hello world”;
  • function sendMessage(){
  •   return globalVariable; // can access globalVariable since it’s written in global space
  • }
  • function sendMessage2(){
  •   return sendMessage(); // Can access sendMessage function since it’s written in global space
  • }
  • sendMessage2();  // 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.

  • function awesomeFunction(){
  •   var a = 2;
  •   var multiplyBy2 = function(){
  •     console.log(a*2); // Can access variable “a” since a and multiplyBy2 both are written inside the same function
  •   }
  • }
  • console.log(a); // Throws reference error since a is written in local scope and cannot be accessed outside
  • multiplyBy2(); // Throws reference error since multiplyBy2 is written in local scope

Block 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.

  • {
  •   let x = 45;
  • }
  • console.log(x); // Gives reference error since x cannot be accessed outside of the block
  • for(let i=0; i<2; i++){
  •   // do something
  • }
  • console.log(i); // Gives reference error since i cannot be accessed outside of the for loop block

Scope Chain

  • var y = 24;
  • function favFunction(){
  •   var x = 667;
  •   var anotherFavFunction = function(){
  •     console.log(x); // Does not find x inside anotherFavFunction, so looks for variable inside favFunction, outputs 667
  •   }
  •   var yetAnotherFavFunction = function(){
  •     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 24
  •   }
  •   anotherFavFunction();
  •   yetAnotherFavFunction();
  • }
  • favFunction();

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, reference error is thrown.

14. Explain Closures in JavaScript.

Ans:

Closures is an ability of a function to remember the variables and functions that are declared in its outer scope.

  • var Person = function(pName){
  •   var name = pName;
  •   this.getName = function(){
  •     return name;
  •   }
  • }
  • var person = new Person(“Neelesh”);
  • console.log(person.getName());

Let’s understand closures by example:

  • function randomFunc(){
  •   var obj1 = {name:”Vivian”, age:45};
  •   return function(){
  •     console.log(obj1.name + ” is “+ “awesome”); // Has access to obj1 even when the randomFunc function is executed
  •   }
  • }
  • var initialiseClosure = randomFunc(); // Returns a function
  • initialiseClosure(); 

Let’s understand the code above,

The function randomFunc() gets executed and returns a function when we assign it to a variable:

var initialiseClosure = randomFunc();

The returned function is then executed when we invoke initialiseClosure:

initialiseClosure(); 

The line of code above outputs “Vivian is awesome” and this is possible because of closure.

When the function randomFunc() runs, it sees that the returning function is using the variable obj1 inside it:

console.log(obj1.name + ” is “+ “awesome”);

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.

15. What are object prototypes?

Ans:

All javascript objects inherit properties from a prototype.

For example,

Date objects inherit properties from the Date prototype

Math objects inherit properties from the Math prototype

Array objects inherit properties from the Array prototype.

On top of the chain is Object.prototype. Every prototype inherits properties and methods from the Object.prototype.

A prototype is a blueprint of an object. Prototype allows us to use properties and methods on an object even if the properties and methods do not exist on the current object.

Let’s see prototypes help us use methods and properties:

  • var arr = [];
  • arr.push(2);
  • console.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 being 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.

16. What are callbacks?

Ans:

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:

  • function divideByHalf(sum){
  •   console.log(Math.floor(sum / 2));
  • }
  • function multiplyBy2(sum){
  •   console.log(sum * 2);
  • }
  • function operationOnSum(num1,num2,operation){
  •   var sum = num1 + num2;
  •   operation(sum);
  • }
  • operationOnSum(3, 3, divideByHalf); // Outputs 3
  • operationOnSum(5, 5, multiplyBy2); // Outputs 20

In the code above, we are performing mathematical operations on the sum of two numbers.

The operationOnSum function takes 3 arguments, first number, second number, and the operation that is to be performed on their sum (callback) .

Both divideByHalf and multiplyBy2 functions are used as callback functions in the code above.

These callback functions will be executed only after the function operationOnSum is executed.

Therefore, callback is a function that will be executed after another function gets executed.

17.What is memoization?

Ans:

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:

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:

  • function addTo256(num){
  •   return num + 256;
  • }
  • addTo256(20); // Returns 276
  • addTo256(40); // Returns 296
  • addTo256(20); // Returns 276

In 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:

  • function memoizedAddTo256(){
  •   var cache = {};
  •   return function(num){
  •     if(num in cache){
  •       console.log(“cached value”);
  •       return cache[num]
  •     }
  •     else{
  •       cache[num] = num + 256;
  •       return cache[num];
  •     }
  •   }
  • }
  • var memoizedFunc = memoizedAddTo256();
  • memoizedFunc(20); // Normal return
  • memoizedFunc(20); // Cached return

In the code above, if we run memoizedFunc function with the same parameter, instead of computing the result again, it returns the cached result.

Although using memoization saves time, it results in larger consumption of memory since we are storing all the computed results.

18. What is recursion in a programming language?

Ans:

Recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.

  • function add(number) {
  •   if (number <= 0) {
  •     return 0;
  •   } else {
  •     return number + add(number – 1);
  •   }
  • }
  • add(3) => 3 + add(2)
  •           3 + 2 + add(1)
  •           3 + 2 + 1 + add(0)
  •           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:

  • function computeSum(arr){
  •   if(arr.length === 1){
  •     return arr[0];
  •   }
  •   else{
  •     return arr.pop() + computeSum(arr);
  •   }
  • }
  • computeSum([7, 8, 9, 99]); // Returns 123

19. What is the use of a constructor function in javascript?

Ans:

Constructor functions are used to create objects in javascript.

20. When do we use constructor functions?

Ans:

If we want to create multiple objects having similar properties and methods, constructor functions are used.

Name of a constructor function should always be written in Pascal Notation: every word should start with a capital letter.

Example:

  • function Person(name,age,gender){
  •   this.name = name;
  •   this.age = age;
  •   this.gender = gender;
  • }
  • var person1 = new Person(“Vivek”, 76, “male”);
  • console.log(person1);
  • var person2 = new Person(“Courtney”, 34, “female”);
  • console.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:
  • var 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.

21. What is DOM?

Ans:

DOM stands for Document Object Model.

DOM is a programming interface for HTML and XML documents.

When the browser tries to render a HTML document, it creates an object based on the HTML document called DOM. Using this DOM, we can manipulate or change various elements inside the HTML document.

Example of how HTML code gets converted to DOM:

DOM

22. What are arrow functions?

Ans:

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:

  • / Traditional Function Expression
  • var add = function(a,b){
  •   return a + b;
  • }
  • // Arrow Function Expression
  • var 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.

  • // Traditional function expression
  • var multiplyBy2 = function(num){
  •   return num * 2;
  • }
  • // Arrow function expression
  • var 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.

  • var obj1 = {
  •   valueOfThis: function(){
  •     return this;
  •   }
  • }
  • var obj2 = {
  •   valueOfThis: ()=>{
  •     return this;
  •   }
  • }
  • obj1.valueOfThis(); // Will return the object obj1
  • obj2.valueOfThis(); // Will return window/global object

The biggest difference between the traditional function expression and the arrow function, is the handling of the 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.

The 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.

23. Differences between declaring variables using var, let and const.

Ans:

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.

keywordconstletvar
global scopenonoyes
function scopeyesyesyes
block scopeyesyesno
can be reassignednoyesyes

24. What is the rest parameter and spread operator?

Ans:

Both rest parameters and spread operators were introduced in the ES6 version of javascript.

Rest parameter ( … )

It provides an improved way of handling parameters of a function.

Using the rest parameter syntax, we can create functions that can take a variable number of arguments.

Any number of arguments will be converted into an array using the rest parameter.

It also helps in extracting all or some parts of the arguments.

Rest parameter can be used by applying three dots (…) before the parameters.

Rest parameter should always be used at the last parameter of a function:

  • // Incorrect way to use rest parameter
  • function randomFunc(a,…args,c){
  • //Do something
  • }
  • // Correct way to use rest parameter
  • function randomFunc2(a,b,…args){
  • //Do something
  • }

Spread operator (…)

Although the syntax of spread operator is exactly the same as the rest parameter, spread operator is used to spread an array, and object literals. We also use spread operators where one or more arguments are expected in a function call.

  • function addFourNumbers(num1,num2,num3,num4){
  •   return num1 + num2 + num3 + num4;
  • }
  • let fourNumbers = [5, 6, 7, 8];
  • addFourNumbers(…fourNumbers);
  • // Spreads [5,6,7,8] as 5,6,7,8
  • let array1 = [3, 4, 5, 6];
  • let clonedArray1 = […array1];
  • // Spreads the array into 3,4,5,6
  • console.log(clonedArray1); // Outputs [3,4,5,6]
  • let obj1 = {x:’Hello’, y:’Bye’};
  • let clonedObj1 = {…obj1}; // Spreads and clones obj1
  • console.log(obj1);
  • let obj2 = {z:’Yes’, a:’No’};
  • let mergedObj = {…obj1, …obj2}; // Spreads both the objects and merges it
  • console.log(mergedObj);
  • // Outputs {x:’Hello’, y:’Bye’,z:’Yes’,a:’No’};

Key differences between rest parameter and spread operator:

  • Rest parameter is used to take a variable number of arguments and turns 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.

25. What is the use of promises in javascript?

Ans:

Promises are used to handle asynchronous operations in javascript.

Before promises, callbacks were used to handle asynchronous operations. But due to limited functionality of callback, using multiple callbacks to handle asynchronous code can lead to unmanageable code.

Promise object has four states –

  1. 1. Pending – Initial state of promise. This state represents that the promise has neither been fulfilled nor been rejected, it is in the pending state.
  2. 2. Fulfilled – This state represents that the promise has been fulfilled, meaning the async operation is completed.
  3. 3. Rejected – This state represents that the promise has been rejected for some reason, meaning the async operation has failed.
  4. 4. Settled – This state represents that the promise has been either rejected or fulfilled.

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 the 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:

  • function sumOfThreeElements(…elements){
  •   return new Promise((resolve,reject)=>{
  •     if(elements.length > 3 ){
  •       reject(“Only three elements or less are allowed”);
  •     }
  •     else{
  •       let sum = 0;
  •       let i = 0;
  •       while(i < elements.length){
  •         sum += elements[i];
  •         i++;
  •       }
  •       resolve(“Sum has been calculated: “+sum);
  •     }
  •   })
  • }

In the code above, we are calculating the sum of three elements, if the length of elements array is more than 3, promise is rejected, 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:

  • sumOfThreeElements(4, 5, 6)
  • .then(result=> console.log(result))
  • .catch(error=> console.log(error));

In the code above, the promise is fulfilled so the then() method gets executed

  • sumOfThreeElements(7, 0, 33, 41)
  • .then(result => console.log(result))
  • .catch(error=> console.log(error));

In the code above, the promise is rejected hence the catch() method gets executed

26. What are classes in javascript?

Ans:

Introduced 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:

  • // Before ES6 version, using constructor functions
  • function Student(name,rollNumber,grade,section){
  •   this.name = name;
  •   this.rollNumber = rollNumber;
  •   this.grade = grade;
  •   this.section = section;
  • }
  • // Way to add methods to a constructor function
  • Student.prototype.getDetails = function(){
  •   return ‘Name: ${this.name}, Roll no: ${this.rollNumber}, Grade: ${this.grade}, Section:${this.section}’;
  • }
  • let student1 = new Student(“Vivek”, 354, “6th”, “A”);
  • student1.getDetails();
  • // Returns Name: Vivek, Roll no:354, Grade: 6th, Section:A
  • // ES6 version classes
  • class Student{
  •   constructor(name,rollNumber,grade,section){
  •     this.name = name;
  •     this.rollNumber = rollNumber;
  •     this.grade = grade;
  •     this.section = section;
  •   }
  •   // Methods can be directly added inside the class
  •   getDetails(){
  •     return ‘Name: ${this.name}, Roll no: ${this.rollNumber}, Grade:${this.grade}, Section:${this.section}’;
  •   }
  • }
  • let student2 = new Student(“Garry”, 673, “7th”, “C”);
  • student2.getDetails();
  • // Returns Name: Garry, Roll no:673, Grade: 7th, Section:C

Key points to remember about classes:

  • Unlike functions, classes are not hoisted. A class cannot be used before it is declared.
  • A class can inherit properties and methods from other classes by using the extend keyword.
  • All the syntaxes inside the class must follow the strict mode(‘use strict’) of javascript. Error will be thrown if the strict mode rules are not followed.

27. What are generator functions?

Ans:

Introduced in ES6 version, generator functions are a special class of functions.

They can be stopped midway and then continue from where it had stopped.

Generator functions are declared with the function* keyword instead of the normal function keyword:

  • function* genFunc(){
  •   // Perform operation
  • }

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:

  • function normalFunc(){
  •   return 22;
  •   console.log(2); // This line of code does not get executed
  • }

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.

  • function* genFunc(){
  •   yield 3;
  •   yield 4;
  • }
  • genFunc(); // 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:

  • genFunc().next(); // Returns {value: 3,
  • done:false
  • }

As one can see the next method returns an object consisting of 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:

  • function* iteratorFunc() {
  •   let count = 0;
  •   for (let i = 0; i < 2; i++) {
  •       count++;
  •       yield i;
  •   }
  •   return count;
  • }
  • let iterator = iteratorFunc();
  • console.log(iterator.next()); // {value:0,done:false}
  • console.log(iterator.next()); // {value:1,done:false}
  • console.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.

28. Explain WeakSet in javascript.

Ans:

In javascript, 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:

  • Weakset contains only objects and no other type.
  • An object inside the weakset is referenced weakly. This means, if the object inside the weakset does not have a reference, it will be garbage collected.
  • Unlike Set, WeakSet only has three methods, add() , delete() and has() .
  • const newSet = new Set([4, 5, 6, 7]);
  • console.log(newSet);// Outputs Set {4,5,6,7}
  • const newSet2 = new WeakSet([3, 4, 5]); //Throws an error
  • let obj1 = {message:”Hello world”};
  • const newSet3 = new WeakSet([obj1]);
  • console.log(newSet3.has(obj1)); // true

29. Explain WeakMap in javascript.

Ans:

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:

  • The keys and values in weakmap should always be an object.
  • If there are no references to the object, the object will be garbage collected.
  • const map1 = new Map();
  • map1.set(‘Value’, 1);
  • const map2 = new WeakMap();
  • map2.set(‘Value’, 2.3); // Throws an error
  • let obj = {name:”Vivek”};
  • const map3 = new WeakMap();
  • map3.set(obj, {age:23});

30. What is Object Destructuring?

Ans:

Object Destructuring is a new and cleaner way of getting or extracting values from an object or an array.

Suppose we have an object that looks like this.

  • const employee = {
  •   firstName: “Marko”,
  •   lastName: “Polo”,
  •   position: “Software Developer”,
  •   yearHired: 2017
  • };

The old way of getting properties from an object is we make a variable that has the same name as the object property. This way is a hassle because we’re making a new variable for every property. Imagine we have a big object with lots of properties and methods using this way in extracting properties will be irritating.

  • var firstName = employee.firstName;
  • var lastName = employee.lastName;
  • var position = employee.position;
  • var yearHired = employee.yearHired;

If we use object destructuring it looks cleaner and takes a little time than the old way. The syntax for object destructuring is that if we are getting properties in an object we use the {} and inside that, we specify the properties we want to extract and if we are getting data from an array we use the [].

  • let { firstName, lastName, position, yearHired } = employee;

If we want to change the variable name we want to extract we use the propertyName:newName syntax. In this example the value of the fName variable will hold the value of the firstName property and lName variable will hold the value of the lastName property.

  • let { firstName: fName, lastName: lName, position, yearHired } = employee;

We can also have default values when destructuring. In this example, if the firstName property holds an undefined value in the object then when we destructure the firstName variable will hold a default of “Mark”.

  • let { firstName = “Mark”, lastName: lName, position, yearHired } = employee;

31. What is a Temporal Dead Zone?

Ans:

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:

  • x = 23; // Gives reference error
  • let x;
  • function anotherRandomFunc(){
  •   message = “Hello”; // Throws a reference error
  •   let message;
  • }
  • anotherRandomFunc();

In the code above, both in global scope and functional scope, we are trying to access variables which have not been declared yet. This is called the Temporal Dead Zone .

32. Name some of the JavaScript features

Ans:

Following are the features of JavaScript −

  • JavaScript is a lightweight, interpreted programming language.
  • JavaScript is designed for creating network-centric applications.
  • JavaScript is complementary to and integrated with Java.
  • JavaScript is complementary to and integrated with HTML.
  • JavaScript is open and cross-platform.

33. What are the advantages of using JavaScript?

Ans:

Following are the advantages of using JavaScript −

  1. 1. Less server interaction − You can validate user input before sending the page off to the server. This saves server traffic, which means less load on your server.
  2. 2. Immediate feedback to the visitors − They don’t have to wait for a page reload to see if they have forgotten to enter something.
  3. 3. Increased interactivity − You can create interfaces that react when the user hovers over them with a mouse or activates them via the keyboard.
  4. 4. Richer interfaces − You can use JavaScript to include such items as drag-and-drop components and sliders to give a Rich Interface to your site visitors.

34. What are disadvantages of using JavaScript?

Ans:

We can not treat JavaScript as a full fledged programming language. It lacks the following important features −

  • Client-side JavaScript does not allow the reading or writing of files. This has been kept for security reasons.
  • JavaScript can not be used for Networking applications because there is no such support available.
  • JavaScript doesn’t have any multithreading or multi process capabilities.

35. Is JavaScript a case-sensitive language?

Ans:

Yes! JavaScript is a case-sensitive language. This means that language keywords, variables, function names, and any other identifiers must always be typed with a consistent capitalization of letters.

Course Curriculum

Get Trained with JavaScript Training from Top-Rated Industry Experts

  • Instructor-led Sessions
  • Real-life Case Studies
  • Assignments
Explore Curriculum

36. How can you create an Object in JavaScript?

Ans:

JavaScript supports the Object concept very well. You can create an object using the object literal as follows −

  • var emp = {
  •    name: “Zara”,
  •    age: 10
  • };

37. How can you read properties of an Object in JavaScript?

Ans:

You can write and read properties of an object using the dot notation as follows 

  • / Getting object properties
  • emp.name  // ==> Zara
  • emp.age   // ==> 10
  • // Setting object properties
  • emp.name = “Daisy”  // <== Daisy
  • emp.age  =  20      // <== 20

How can you create an Array in JavaScript?

You can define arrays using the array literal as follows −

  • var x = [];
  • var y = [1, 2, 3, 4, 5];

How to read elements of an array in JavaScript?

An array has a length property that is useful for iteration. We can read elements of an array as follows −

  • var x = [1, 2, 3, 4, 5];
  • for (var i = 0; i < x.length; i++) {
  •    // Do something with x[i]
  • }

38. What is a named function in JavaScript? How to define a named function?

Ans:

A named function has a name when it is defined. A named function can be defined using function keyword as follows −

  • function named(){
  •    // do some stuff here
  • }

39. How many types of functions JavaScript supports?

Ans:

A function in JavaScript can be either named or anonymous.

40. How to define an anonymous function?

Ans:

An anonymous function can be defined in a similar way as a normal function but it would not have any name.

41. Can you assign an anonymous function to a variable?

Ans:

Yes! An anonymous function can be assigned to a variable.

42. Can you pass an anonymous function as an argument to another function?

Ans:

Yes! An anonymous function can be passed as an argument to another function.

43. What is an argument object in JavaScript?

Ans:

JavaScript variable arguments represent the arguments passed to a function.

44. How can you get the type of arguments passed to a function? & How can you get the total number of arguments passed to a function?

Ans:

Using typeof operator, we can get the type of arguments passed to a function.

Using arguments.length property, we can get the total number of arguments passed to a function.

For Example,

  • function func(x){
  •    console.log(typeof x, arguments.length);
  • }
  • func();                //==> “undefined”, 0
  • func(1);               //==> “number”, 1
  • func(“1”, “2”, “3”);   //==> “string”, 3

45. What is ECMAScript?

Ans:

ECMAScript is a standard for making scripting languages which means that JavaScript follows the specification changes in ECMAScript standard because it is the blueprint of JavaScript.

46. How can you get the reference of a caller function inside a function?

Ans:

The arguments object has a callee property, which refers to the function you’re inside of.

For example,

  • function func() {
  •    return arguments.callee; 
  • }
  • func();                // ==> func

47. What is the purpose of ‘this’ operator in JavaScript?

Ans:

JavaScript famous keyword this always refers to the current context.

48. What are the valid scopes of a variable in JavaScript?

Ans:

The scope of a variable is the region of your program in which it is defined. The JavaScript variable will have only two scopes.

Global Variables − A global variable has global scope which means it is visible everywhere in your JavaScript code.

Local Variables − A local variable will be visible only within a function where it is defined. Function parameters are always local to that function.

49.Which type of variable among global and local, takes precedence over others if names are the same?

Ans:

A local variable takes precedence over a global variable with the same name.

50. Which built-in method returns the character at the specified index?

Ans:

charAt() method returns the character at the specified index.

51. Which built-in method combines the text of two strings and returns a new string?

Ans:

concat() method returns the character at the specified index.

52. Which built-in method calls a function for each element in the array?

Ans:

forEach() method calls a function for each element in the array.

53. Which built-in method returns the index within the calling String object of the first occurrence of the specified value?

Ans:

indexOf() method returns the index within the calling String object of the first occurrence of the specified value, or −1 if not found.

54. Which built-in method returns the length of the string?

Ans:

length() method returns the length of the string.

55. Which built-in method removes the last element from an array and returns that element?

Ans:

pop() method removes the last element from an array and returns that element.

Course Curriculum

Gain In-Depth Knowledge On JavaScript Certification Course to Build Your Skills

Weekday / Weekend BatchesSee Batch Details

56. Which built-in method adds one or more elements to the end of an array and returns the new length of the array?

Ans:

push() method adds one or more elements to the end of an array and returns the new length of the array.

57. Which built-in method reverses the order of the elements of an array?

Ans:

reverse() method reverses the order of the elements of an array −− the first becomes the last, and the last becomes the first.

58. Which built-in method sorts the elements of an array?

Ans:

sort() method sorts the elements of an array.

59. Which built-in method returns the characters in a string beginning at the specified location?

Ans:

substr() method returns the characters in a string beginning at the specified location through the specified number of characters.

60. Which built-in method returns the calling string value converted to lowercase?

Ans:

toLowerCase() method returns the calling string value converted to lowercase.

61. Which built-in method returns the calling string value converted to uppercase?

Ans:

toUpperCase() method returns the calling string value converted to upper case.

62. Which built-in method returns the string representation of the number’s value?

Ans:

toString() method returns the string representation of the number’s value.

63. What are the variable naming conventions in JavaScript?

Ans:

While naming your variables in JavaScript keep following rules in mind. You should not use any of the JavaScript reserved keywords as variable names. These keywords are mentioned in the next section. For example, break or boolean variable names are not valid. JavaScript variable names should not start with a numeral (0-9). They must begin with a letter or the underscore character. 

For example, 123test is an invalid variable name but _123test is a valid one.

JavaScript variable names are case sensitive.

For example, Name and name are two different variables.

64. How does the typeof operator work?

Ans:

The typeof is a unary operator that is placed before its single operand, which can be of any type. Its value is a string indicating the data type of the operand.

The typeof operator evaluates to “number”, “string”, or “boolean” if its operand is a number, string, or boolean value and returns true or false based on the evaluation.

65. What typeof returns for a null value?

Ans:

It returns “object”.

66. Can you access Cookie using javascript?

Ans:

JavaScript can also manipulate cookies using the cookie property of the Document object. JavaScript can read, create, modify, and delete the cookie or cookies that apply to the current web page.

67. How to create a Cookie using JavaScript?

Ans:

The simplest way to create a cookie is to assign a string value to the document.cookie object, which looks like this −

Syntax −

  • document.cookie = “key1 = value1; key2 = value2; expires = date”;

Here the expiry attribute is an option. If you provide this attribute with a valid date or time then the cookie will expire at the given date or time and after that cookies’ value will not be accessible.

68. How to read a Cookie using JavaScript?

Ans:

Reading a cookie is just as simple as writing one, because the value of the document.cookie object is the cookie. So you can use this string whenever you want to access the cookie. The document.cookie string will keep a list of name = value pairs separated by semicolons, where name is the name of a cookie and value is its string value.

You can use strings’ split() function to break the string into keys and values.

69. How to delete a Cookie using JavaScript?

Ans:

Sometimes you will want to delete a cookie so that subsequent attempts to read the cookie return nothing. To do this, you just need to set the expiration date to a time in the past.

70. How to redirect a url using JavaScript?

Ans:

This is very simple to do a page redirect using JavaScript at the client side. To redirect your site visitors to a new page, you just need to add a line in your head section as follows −

  • <head>
  • <script type=”text/javascript”>
  • <!–
  •    window.location=”http://www.newlocation.com”;
  • //–>
  • </script>
  • </head>

71. How to print a web page using javascript?

Ans:

JavaScript helps you to implement this functionality using the print function of window object. The JavaScript print function window.print() will print the current web page when executed.

72. What is a Date object in JavaScript?

Ans:

The Date object is a datatype built into the JavaScript language. Date objects are created with the new Date( ).

Once a Date object is created, a number of methods allow you to operate on it. Most methods simply allow you to get and set the year, month, day, hour, minute, second, and millisecond fields of the object, using either local time or UTC (universal, or GMT) time.

73. What is the Number object in JavaScript?

Ans:

The Number object represents a numerical date, either integers or floating-point numbers. In general, you do not need to worry about Number objects because the browser automatically converts number literals to instances of the number class.

Syntax −

Creating a number object

  • var val = new Number(number);

If the argument cannot be converted into a number, it returns NaN (Not-a-Number).

74. How to handle exceptions in JavaScript?

Ans:

The latest versions of JavaScript added exception handling capabilities. JavaScript implements the try…catch…finally construct as well as the throw operator to handle exceptions. You can catch programmer-generated and runtime exceptions, but you cannot catch JavaScript syntax errors.

75. What is the purpose of onError event handler in JavaScript?

Ans:

The onerror event handler was the first feature to facilitate error handling for JavaScript. The error event is fired on the window object whenever an exception occurs on the page.

The onerror event handler provides three pieces of information to identify the exact nature of the error −

  • Error message − The same message that the browser would display for the given error.
  • URL − The file in which the error occurred.
  • Line number − The line number in the given URL that caused the error.
javascript Sample Resumes! Download & Edit, Get Noticed by Top Employers! Download

76. What is Event Propagation?

Ans:

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent’s parent until it reaches all the way to the window while in the Capturing Phase the event starts from the window down to the element that triggered the event or the event.target.

Event Propagation has three phases.

  1. 1. Capturing Phase – the event starts from the window then goes down to every element until it reaches the target element.
  2. 2. Target Phase – the event has reached the target element.
  3. 3. Bubbling Phase – the event bubbles up from the target element then goes up every element until it reaches the window.
Event-Propagation

77. What’s Event Bubbling?

Ans:

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In the Bubbling Phase, the event bubbles up or it goes to its parent, to its grandparents, to its grandparent’s parent until it reaches all the way to the window.

If we have an example markup like this.

  • <div class=”grandparent”>
  •     <div class=”parent”>
  •       <div class=”child”>1</div>
  •     </div>
  •   </div>

And our js code.

  • function addEvent(el, event, callback, isCapture = false) {
  •   if (!el || !event || !callback || typeof callback !== ‘function’) return;
  •   if (typeof el === ‘string’) {
  •     el = document.querySelector(el);
  •   };
  •   el.addEventListener(event, callback, isCapture);
  • }
  • addEvent(document, ‘DOMContentLoaded’, () => {
  •   const child = document.querySelector(‘.child’);
  •   const parent = document.querySelector(‘.parent’);
  •   const grandparent = document.querySelector(‘.grandparent’);
  •   addEvent(child, ‘click’, function (e) {
  •     console.log(‘child’);
  •   });
  •   addEvent(parent, ‘click’, function (e) {
  •     console.log(‘parent’);
  •   });
  •   addEvent(grandparent, ‘click’, function (e) {
  •     console.log(‘grandparent’);
  •   });
  •   addEvent(document, ‘click’, function (e) {
  •     console.log(‘document’);
  •   });
  •   addEvent(‘html’, ‘click’, function (e) {
  •     console.log(‘html’);
  •   })
  •   addEvent(window, ‘click’, function (e) {
  •     console.log(‘window’);
  •   })
  • });

The addEventListener method has a third optional parameter useCapture with a default value of false the event will occur in the Bubbling phase if true the event will occur in the Capturing Phase. If we click on the child element it logs child,parent,grandparent, html, document and window respectively on the console. This is Event Bubbling.

78. What’s Event Capturing?

Ans:

When an event occurs on a DOM element, that event does not entirely occur on that just one element. In Capturing Phase, the event starts from the window all the way down to the element that triggered the event.

If we have an example markup like this.

  • <div class=”grandparent”>
  •     <div class=”parent”>
  •       <div class=”child”>1</div>
  •     </div>
  •   </div>

And our js code.

  • function addEvent(el, event, callback, isCapture = false) {
  •   if (!el || !event || !callback || typeof callback !== ‘function’) return;
  •   if (typeof el === ‘string’) {
  •     el = document.querySelector(el);
  •   };
  •   el.addEventListener(event, callback, isCapture);
  • }
  • addEvent(document, ‘DOMContentLoaded’, () => {
  •   const child = document.querySelector(‘.child’);
  •   const parent = document.querySelector(‘.parent’);
  •   const grandparent = document.querySelector(‘.grandparent’);
  •   addEvent(child, ‘click’, function (e) {
  •     console.log(‘child’);
  •   }, true);
  •   addEvent(parent, ‘click’, function (e) {
  •     console.log(‘parent’);
  •   }, true);
  •   addEvent(grandparent, ‘click’, function (e) {
  •     console.log(‘grandparent’);
  •   }, true);
  •   addEvent(document, ‘click’, function (e) {
  •     console.log(‘document’);
  •   }, true);
  •   addEvent(‘html’, ‘click’, function (e) {
  •     console.log(‘html’);
  •   }, true)
  •   addEvent(window, ‘click’, function (e) {
  •     console.log(‘window’);
  •   }, true)
  • });

The addEventListener method has a third optional parameter useCapture with a default value of false the event will occur in the Bubbling phase if true the event will occur in the Capturing Phase. If we click on the child element it logs the window, document,html, grandparent and parent and child respectively on the console. This is Event Capturing.

79.What’s the difference between event.preventDefault() and event.stopPropagation() methods?

Ans:

The event.preventDefault() method prevents the default behavior of an element. If used in a form element it prevents it from submitting. If used in an anchor element it prevents it from navigating. If used in a context menu it prevents it from showing or displaying. While the event.stopPropagation() method stops the propagation of an event or it stops the event from occurring in the bubbling or capturing phase.

80. How to know if the event.preventDefault() method was used in an element?

Ans:

We can use the event.defaultPrevented property in the event object. It returns a boolean indicating if the event.preventDefault() was called in a particular element.

81. Why does this code obj.someprop.x throw an error?

const obj = {};

console.log(obj.someprop.x);

Ans:

Obviously, this throws an error due to the reason we are trying to access a

x property in the someprop property which has an undefined value. Remember properties in an object which does not exist in itself and its prototype has a default value of undefined and undefined has no property x.

82. What is event.target ?

Ans:

In simplest terms, the event.target is the element on which the event occurred or the element that triggered the event.

Sample HTML Markup.

  • <div onclick=”clickFunc(event)” style=”text-align: center;margin:15px;
  • border:1px solid red;border-radius:3px;”>
  •     <div style=”margin: 25px; border:1px solid royalblue;border-radius:3px;”>
  •         <div style=”margin:25px;border:1px solid skyblue;border-radius:3px;”>
  •           <button style=”margin:10px”>
  •              Button
  •           </button>
  •         </div>
  •     </div>
  •   </div>
  • Sample JavaScript.
  • function clickFunc(event) {
  •   console.log(event.target);
  • }

If you click the button it will log the button markup even though we attach the event on the outermost div it will always log the button so we can conclude that the event.target is the element that triggered the event.

83. What is event.currentTarget?

Ans:

The event.currentTarget is the element on which we attach the event handler explicitly.

Sample HTML Markup.

  • <div onclick=”clickFunc(event)” style=”text-align: center;margin:15px;
  • border:1px solid red;border-radius:3px;”>
  •     <div style=”margin: 25px; border:1px solid royalblue;border-radius:3px;”>
  •         <div style=”margin:25px;border:1px solid skyblue;border-radius:3px;”>
  •           <button style=”margin:10px”>
  •              Button
  •           </button>
  •         </div>
  •     </div>
  •   </div>

And changing out the JS a little bit.

  • function clickFunc(event) {
  •   console.log(event.currentTarget);
  • }

If you click the button it will log the outermost div markup even though we click the button. In this example, we can conclude that the event.currentTarget is the element on which we attach the event handler.

84. Why does it return false when comparing two similar objects in JavaScript?

Ans:

Suppose we have an example below.

  • let a = { a: 1 };
  • let b = { a: 1 };
  • let c = a;
  • console.log(a === b); // logs false even though they have the same property
  • console.log(a === c); // logs true hmm

JavaScript compares objects and primitives differently. In primitives it compares them by value while in objects it compares them by reference or the address in memory where the variable is stored. That’s why the first console.log statement returns false and the second console.log statement returns true. a and c have the same reference and a and b are not.

85. What does that !! operator do?

Ans:

The Double NOT operator or !! coerces the value on the right side into a boolean. basically it’s a fancy way of converting a value into a boolean.

  • console.log(!!null); //logs false
  • console.log(!!undefined); //logs false
  • console.log(!!”); //logs false
  • console.log(!!0); //logs false
  • console.log(!!NaN); //logs false
  • console.log(!!’ ‘); //logs true
  • console.log(!!{}); //logs true
  • console.log(!![]); //logs true
  • console.log(!!1); //logs true
  • console.log(!![].length); //logs false

86. How to evaluate multiple expressions in one line?

Ans:

We can use the , or comma operator to evaluate multiple expressions in one line. It evaluates from left-to-right and returns the value of the last item on the right or the last operand.

  • let x = 5;
  • x = (x++ , x = addFive(x), x *= 2, x -= 5, x += 10);
  • function addFive(num) {
  •   return num + 5;
  • }

If you log the value of x it would be 27. First, we increment the value of x it would be 6, then we invoke the function addFive(6) and pass the 6 as a parameter and assign the result to x the new value of x would be 11. After that, we multiply the current value of x to 2 and assign it to x the updated value of x would be 22. Then, we subtract the current value of x to 5 and assign the result to x the updated value would be 17. And lastly, we increment the value of x by 10 and assign the updated value to x now the value of x would be 27.

87. What are the falsy values in JavaScript?

Ans:

  • const falsyValues = [”, 0, null, undefined, NaN, false];

falsy values are values that when converted to boolean becomes false.

88. How to check if a value is falsy?

Ans:

Use the Boolean function or the Double NOT operator !!

89. What is the use of the Function.prototype.apply method?

Ans:

The apply invokes a function specifying the this or the “owner” object of that function on that time of invocation.

  • const details = {
  •   message: ‘Hello World!’
  • };
  • function getMessage(){
  •   return this.message;
  • }
  • getMessage.apply(details); // returns ‘Hello World!’

This method works like Function.prototype.call the only difference is how we pass arguments. In apply we pass arguments as an array.

  • const person = {
  •   name: “Marko Polo”
  • };
  • function greeting(greetingMessage) {
  •   return `${greetingMessage} ${this.name}`;
  • }
  • greeting.apply(person, [‘Hello’]); // returns “Hello Marko Polo!”

90. What is the use of the Function.prototype.call method?

Ans:

The call invokes a function specifying the this or the “owner” object of that function on that time of invocation.

  • const details = {
  •   message: ‘Hello World!’
  • };
  • function getMessage(){
  •   return this.message;
  • }
  • getMessage.call(details); // returns ‘Hello World!’

This method works like Function.prototype.apply the only difference is how we pass arguments. In call we pass directly the arguments separating them with a comma , for every argument.

  • const person = {
  •   name: “Marko Polo”
  • };
  • function greeting(greetingMessage) {
  •   return `${greetingMessage} ${this.name}`;
  • }
  • greeting.call(person, ‘Hello’); // returns “Hello Marko Polo!”

91. What’s the difference between Function.prototype.apply and Function.prototype.call?

Ans:

The only difference between apply and call is how we pass the arguments in the function being called. In apply we pass the arguments as an array and in call we pass the arguments directly in the argument list.

  • const obj1 = {
  •  result:0
  • };
  • const obj2 = {
  •  result:0
  • };
  • function reduceAdd(){
  •    let result = 0;
  •    for(let i = 0, len = arguments.length; i < len; i++){
  •      result += arguments[i];
  •    }
  •    this.result = result;
  • }
  • reduceAdd.apply(obj1, [1, 2, 3, 4, 5]); // returns 15
  • reduceAdd.call(obj2, 1, 2, 3, 4, 5); // returns 15

92. What is the usage of Function.prototype.bind?

Ans:

The bind method returns a new function that is bound

to a specific this value or the “owner” object, So we can use it later in our code. The call,apply methods invokes the function immediately instead of returning a new function like the bind method.

  • import React from ‘react’;
  • class MyComponent extends React.Component {
  •      constructor(props){
  •           super(props); 
  •           this.state = {
  •              value : “”
  •           }  
  •           this.handleChange = this.handleChange.bind(this); 
  •           // Binds the “handleChange” method to the “MyComponent” component
  •      }
  •      handleChange(e){
  •        //do something amazing here
  •      }
  •      render(){
  •         return (
  •               <>
  •                 <input type={this.props.type}
  •                         value={this.state.value}
  •                      onChange={this.handleChange}                      
  •                   />
  •               </>
  •         )
  •      }
  • }

93. What is Functional Programming and what are the features of JavaScript that makes it a candidate as a functional language?

Ans:

Functional Programming is a declarative programming paradigm or pattern on how we build our applications with functions using expressions that calculates a value without mutating or changing the arguments that are passed to it.

JavaScript Array has map, filter, reduce methods which are the most famous functions in the functional programming world because of their usefulness and because they don’t mutate or change the array which makes these functions pure and JavaScript supports Closures and Higher Order Functions which are a characteristic of a Functional Programming Language.

The map method creates a new array with the results of calling a provided callback function on every element in the array.

  • const words = [“Functional”, “Procedural”, “Object-Oriented”];
  • const wordsLength = words.map(word => word.length);

The filter method creates a new array with all elements that pass the test in the callback function.

  • const data = [
  •   { name: ‘Mark’, isRegistered: true },
  •   { name: ‘Mary’, isRegistered: false },
  •   { name: ‘Mae’, isRegistered: true }
  • ];
  • const registeredUsers = data.filter(user => user.isRegistered);

The reduce method applies a function against an accumulator and each element in the array (from left to right) to reduce it to a single value.

  • const strs = [“I”, ” “, “am”, ” “, “Iron”, ” “, “Man”];
  • const result = strs.reduce((acc, currentStr) => acc + currentStr, “”);

94. What are Higher Order Functions?

Ans:

Higher-Order Function are functions that can return a function or receive argument or arguments which have a value of a function.

  • function higherOrderFunction(param,callback){
  •     return callback(param);
  • }

95. Why are functions called First-class Objects?

Ans:

Functions in JavaScript are First-class Objects because they are treated as any other value in the language. They can be assigned to variables, they can be properties of an object which are called methods, they can be an item in array, they can be passed as arguments to a function, and they can be returned as values of a function. The only difference between a function and any other value in JavaScript is that functions can be invoked or called.

96. Implement the Array.prototype.map method by hand.

Ans:

  • function map(arr, mapCallback) {
  •   // First, we check if the parameters passed are right.
  •   if (!Array.isArray(arr) || !arr.length || typeof mapCallback !== ‘function’) { 
  •     return [];
  •   } else {
  •     let result = [];
  •     // We’re making a results array every time we call this function
  •     // because we don’t want to mutate the original array.
  •     for (let i = 0, len = arr.length; i < len; i++) {
  •       result.push(mapCallback(arr[i], i, arr)); 
  •       // push the result of the mapCallback in the ‘result’ array
  •     }
  •     return result; // return the result array
  •   }
  • }

As the MDN description of the Array.prototype.map method.

The map() method creates a new array with the results of calling a provided function on every element in the calling array.

97. Implement the Array.prototype.filter method by hand.

Ans:

  • function filter(arr, filterCallback) {
  •   // First, we check if the parameters passed are right.
  •   if (!Array.isArray(arr) || !arr.length || typeof filterCallback !== ‘function’) 
  •   {
  •     return [];
  •   } else {
  •     let result = [];
  •     // We’re making a results array every time we call this function
  •     // because we don’t want to mutate the original array.
  •     for (let i = 0, len = arr.length; i < len; i++) {
  •       // check if the return value of the filterCallback is true or “truthy”
  •       if (filterCallback(arr[i], i, arr)) { 
  •       // push the current item in the ‘result’ array if the condition is true
  •         result.push(arr[i]);
  •       }
  •     }
  •     return result; // return the result array
  •   }
  • }

As the MDN description of the Array.prototype.filter method.

The filter() method creates a new array with all elements that pass the test implemented by the provided function.

98. Implement the Array.prototype.reduce method by hand.

Ans:

  • function reduce(arr, reduceCallback, initialValue) {
  •   // First, we check if the parameters passed are right.
  •   if (!Array.isArray(arr) || !arr.length || typeof reduceCallback !== ‘function’) 
  •   {
  •     return [];
  •   } else {
  •     // If no initialValue has been passed to the function we’re gonna use the 
  •     let hasInitialValue = initialValue !== undefined;
  •     let value = hasInitialValue ? initialValue : arr[0];
  •     // first array item as the initialValue
  •     // Then we’re gonna start looping at index 1 if there is no 
  •     // initialValue has been passed to the function else we start at 0 if 
  •     // there is an initialValue.
  •     for (let i = hasInitialValue ? 0 : 1, len = arr.length; i < len; i++) {
  •       // Then for every iteration we assign the result of the 
  •       // reduceCallback to the variable value.
  •       value = reduceCallback(value, arr[i], i, arr); 
  •     }
  •     return value;
  •   }
  • }

As the MDN description of the Array.prototype.reduce method.

The reduce() method executes a reducer function (that you provide) on each element of the array, resulting in a single output value.

99. How to create an object without a prototype?

Ans:

We can create an object without a prototype using the Object.create method.

  •   const o1 = {};
  •    console.log(o1.toString()); 
  •    // logs [object Object] get this method to the Object.prototype 
  •    const o2 = Object.create(null);
  •    // the first parameter is the prototype of the object “o2” which in this
  •    // case will be null specifying we don’t want any prototype
  •    console.log(o2.toString());
  •    // throws an error o2.toString is not a function 

100. Why does b in this code become a global variable when you call this function?

function myFunc() {

  let a = b = 0;

}

myFunc();

Ans:

The reason for this is that assignment operator or = has right-to-left associativity or evaluation. What this means is that when multiple assignment operators appear in a single expression they evaluated from right to left. So our code becomes likes this.

  • function myFunc() {
  •   let a = (b = 0);
  • }
  • myFunc();

First, the expression b = 0 evaluated and in this example b is not declared. So, The JS Engine makes a global variable b outside this function after that the return value of the expression b = 0 would be 0 and it’s assigned to the new local variable a with a let keyword.

We can solve this problem by declaring the variables first before assigning them with value.

  • function myFunc() {
  •   let a,b;
  •   a = b = 0;
  • }
  • myFunc();

101. What are the new features in ES6 or ECMAScript 2015?

Ans:

  • Arrow Functions
  • Classes
  • Template Strings
  • Enhanced Object literals
  • Object Destructuring
  • Promises
  • Generators
  • Modules
  • Symbol
  • Proxies
  • Sets
  • Default Function parameters
  • Rest and Spread
  • Block Scoping with let and const

102. What are Template Literals?

Ans:

Template Literals are a new way of making strings in JavaScript. We can make Template Literal by using the backtick or back-quote symbol.

  • /ES5 Version
  • var greet = ‘Hi I\’m Mark’;
  • //ES6 Version
  • let greet = `Hi I’m Mark`;

In the ES5 version, we need to escape the ‘ using the \ to escape the normal functionality of that symbol which in this case is to finish that string value. In Template Literals, we don’t need to do that.

  • //ES5 Version
  • var lastWords = ‘\n’
  •   + ‘   I  \n’
  •   + ‘   Am  \n’
  •   + ‘Iron Man \n’;
  • //ES6 Version
  • let lastWords = `
  •     I
  •     Am
  •   Iron Man   
  • `;

In the ES5 version, we need to add this \n to have a new line in our string. In Template Literals, we don’t need to do that.

  • //ES5 Version
  • function greet(name) {
  •   return ‘Hello ‘ + name + ‘!’;
  • }
  • //ES6 Version
  • const greet = name => {
  •   return `Hello ${name} !`;
  • }

In the ES5 version, If we need to add an expression or value in a string we need to use the + or string concatenation operator. In Template Literals, we can embed an expression using ${expr} which makes it cleaner than the ES5 version.

103. What is the Set object and how does it work?

Ans:

The Set object is an ES6 feature that lets you store unique values, primitives or object references. A value in a Set can only occur once. It checks if a value exists in the set object using the SameValueZero algorithm.

We can make a Set instance using Set constructor and we can optionally pass an Iterable as the initial value.

  • const set1 = new Set();
  • const set2 = new Set([“a”,”b”,”c”,”d”,”d”,”e”]);

We can add a new value into the Set instance using the add method and since the add returns the Set object we can chain add calls. If a value already exists in Set object it will not be added again.

  • set2.add(“f”);
  • set2.add(“g”).add(“h”).add(“i”).add(“j”).add(“k”).add(“k”);
  • // the last “k” will not be added to the set object because it already exists

We can remove a value from the Set instance using the delete method, this method returns a boolean indicating true if a value exists in the Set object and false indicating that value does not exist.

set2.delete(“k”) // returns true because “k” exists in the set object

set2.delete(“z”) // returns false because “z” does not exists in the set object

We can check if a specific value exists in the Set instance using the has method.

set2.has(“a”) // returns true because “a” exists in the set object

set2.has(“z”) // returns false because “z” does not exists in the set object

We can get the length of the Set instance using the size property.

set2.size // returns 10

We can delete or remove all the elements in the Set instance using the clear.

  • set2.clear(); // clears the set data

We can use the Set object for removing duplicate elements in an array.

  • const numbers = [1, 2, 3, 4, 5, 6, 6, 7, 8, 8, 5];
  • const uniqueNums = […new Set(numbers)]; // has a value of [1,2,3,4,5,6,7,8]

104. What is async/await and How does it work?

Ans:

async/await is the new way of writing asynchronous or non-blocking code in JavaScript. It is built on top of Promises. It makes writing asynchronous code more readable and cleaner than Promises and Callbacks. But you must learn the basics of Promises before using this feature because as I said earlier it is built on top of Promises which means it still uses Promises under the hood.

Using Promises.

  • function callApi() {
  •   return fetch(“url/to/api/endpoint”)
  •     .then(resp => resp.json())
  •     .then(data => {
  •       //do something with “data”
  •     }).catch(err => {
  •       //do something with “err”
  •     });
  • }

Note: We’re using the old try/catch statement to catch any errors that happened in any of those async operations inside the try statement.

  • async function callApi() {
  •   try {
  •     const resp = await fetch(“url/to/api/endpoint”);
  •     const data = await resp.json();
  •     //do something with “data”
  •   } catch (e) {
  •     //do something with “err”
  •   }
  • }

The async keyword before the function declaration makes the function return implicitly a Promise.

  • const giveMeOne = async () => 1;
  • giveMeOne()
  •   .then((num) => {
  •     console.log(num); // logs 1
  •   });

The await keyword can only be used inside an async function. Using await keyword in any other function which is not an async function will throw an error. The await keyword awaits the right-hand side expression (presumably a Promise) to return before executing the next line of code.

  • const giveMeOne = async () => 1;
  • function getOne() {
  •   try {
  •     const num = await giveMeOne();
  •     console.log(num);
  •   } catch (e) {
  •     console.log(e);
  •   }
  • }
  • //Throws a Compile-Time Error = Uncaught SyntaxError: await is only valid in an async function
  • async function getTwo() {
  •   try {
  •     const num1 = await giveMeOne(); //finishes this async operation first before going to
  •     const num2 = await giveMeOne(); //this line
  •     return num1 + num2;
  •   } catch (e) {
  •     console.log(e);
  •   }
  • }
  • await getTwo(); // returns 2

Are you looking training with Right Jobs?

Contact Us

Popular Courses