Home >> Interviews Q & A >> JavaScript Interview Questions

JavaScript Interview Questions

JavaScript Interview Questions: Advanced JavaScript Interview Questions and Answers for freshers and experienced. JavaScript, often abbreviated as JS, is a high-level, interpreted programming language.
Javascript Interview Questions
Q:- What is JavaScript?
JavaScript(JS) is an object-based, lightweight and cross-platform, high-level, interpreted case-sensitive scripting language.
Q:- What is Scope? types of Scope in JavaScript?
Scope determines the availability or accessibility or visibility of variables, objects, and functions.
Types of Scope:

There are mainly two type of scope in javascript

  1. Global Scope
  2. Local Scope
    • Block Scope
    • Function Scope
Q:- What is the difference between let and var?
The difference between let and var is of Scoping.
  1. let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.
  2. var is rather a keyword which defines a variable globally regardless of block scope.

The both are very similar when used like the following, outside a function block.

let x = 'JavaScript interview questions';  // globally scoped
var y = 'Advanced JavaScript'; // globally scoped
Key Points:

Window Object: However, global variables defined with let will not be added as properties on the global window object.

let x = 'JavaScript interview questions';  // globally scoped
var y = 'Advanced JavaScript'; // globally scoped

console.log(window.x); // undefined
console.log(window.y); // 'Advanced JavaScript'

Block Scope: let has block level scope.

Redeclaration: let and const variables cannot be re-declared while var variable can be re-declared in the same scope.

'use strict';
let x = 'Hi, FullStackTutorials';
let x = 'Hello, FullStackTutorials'; // SyntaxError: Identifier 'x' has already been declared
'use strict';
var y = 'Hi, FullStackTutorials';
var y = 'Hello, FullStackTutorials'; // No problem, 'y' is replaced.

Let's read more about - const in JavaScript ES6

Q:- What is difference between Function Declaration and Function Expression?
Function Declaration:
function myFunc(name) {
 return `Hello ${name}, Welcome to Advanced JavaScript Interview Questions`;
}
console.log(myFunc("User"));

//Output
Hello User, Welcome to Advanced JavaScript Interview Questions
Function Expression:

A function expression can be stored in a variable and the variable can be used as a function

var myFunc = function (name) {
 return `Hello ${name}, Welcome to Advanced JavaScript Interview Questions`;
};
console.log(myFunc("User"));

//Output
Hello User, Welcome to Advanced JavaScript Interview Questions

There are many benefits of using function expressions

  1. It can be used as Closure
  2. It can be passed as arguments to other Function
  3. It cab be used as Immediately Invoked Function Expressions (IIFE)
Function Expressions can not be Hoisted.
Q:- What is Immediately Invoked Function Expressions (IIFE) in JavaScript?
  1. An IIFE (Immediately Invoked Function Expression) is a JavaScript function that runs as soon as it is defined.
  2. It is a design pattern which is also known as a Self-Executing Anonymous Function
(function () {
    statements
})();

Example

var sum = (function (a,b) {
    return a+b; 
})(2,3); 
console.log(sum); // 5

var sum = ((a,b) => {
    return a+b; 
})(2,3); 
console.log(sum); // 5

(function (a,b) {
    console.log(a+b); 
})(2,3);   // 5
Q:- What is Hoisting in JavaScript?
  • Hoisting is JavaScript's default behavior of moving all declarations to the top of the current scope (to the top of the current script or the current function).
  • variables and function declarations are moved to the top of their scope before code execution.
  • In JavaScript, a variable can be declared after it has been used. In other words, a variable can be used before it has been declared.
x = 5; 
console.log(x); // Output: 5
var x; 
JavaScript only hoists declarations, not initializations.
var x = 5; 
console.log('value is ' + x + ' and '+ y);
var y = 10; 

//Output: value is 5 and undefined
Note - Because variable y is not initialized before it is being used.

You may also like - Javascript ES6 Interview Questions
Q:- Is JavaScript a case sensitive language?

Yes, JavaScript is case sensitive.

Q:- What is functions JavaScript?

1. Anonymous Function - This type of function has no name.

var anonmFunc = function(){
  console.log("Advanced JavaScript Interview Questions and Answers");
}

2. Regular Named Function - This function is named properly and specifically.

function myFunc(){
  console.log("Advanced JavaScript Interview Questions and Answers");
}

3. Arrow Function - Arrow function (kind of anonymous function) is part of ES6.

Arrow functions is best suited with anything that requires this to be bound to the context, and not the function itself.

Benefits of Arrow Functions
  1. Shorter Syntax
  2. No binding of this
//Regular Function
function myFunc(){
  console.log("Advanced JavaScript Interview Questions and Answers");
}

//Arrow Function
var myFunc = () => {
 console.log("Advanced JavaScript Interview Questions and Answers");
}
Unlike a regular function, an arrow function does not bind this. Instead, this is bound lexically (i.e. this keeps it's meaning from its original context).

An arrow function does not have its own this. this value of the enclosing lexical scope is used by arrow functions. So if this is not present in current scope, an arrow function ends up looking into lexical scope.

You may also like - React.js Interview Questions
Q:- What is Objects in JavaScript?
Object is an unordered collection of data in the form of key:value pairs.
  • A JavaScript object is an entity having State and Behavior (Properties and Methods).
  • JavaScript is a prototype based language, so everything is an Object.
//A Simple Object Example

var TV = { 
  Name : "TV Name",
  Price: "15000",
  Color: "Black",
  SwitchON : function (){
		// Code Snippet
  },
  SwitchOFF : function (){
		// Code Snippet
  }
} 
Q:- How many ways you can create an Object in JavaScript?

There are many ways to define or create an object in JavaScript.

Different ways of creating an Object in javascript:-
  1. Object Literals
  2. Object Constructor
  3. Function Based
  4. Using Function Prototype
1. Object Literals:
var person = { 
  name : "FullStackTutorials",
  getName : function (){
	return this.name
  } 
} 
2. Object Constructor:
// Using Object() Method

var person = new Object();
person.name = "FullStackTutorials",
person.getName = function(){
  return this.name ; 
};


// Using Object.create() method:
var person = Object.create(null);
3. Using Function:
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
} 

var obj = new Person("FullStackTutorials");
console.log(obj);
4. Using Function Prototype:
function Person(name){
  this.name = name;
} 
Person.prototype.getName = function(){
  return this.name
} 
Q:- What is the difference between Object.create and new Object?

Object.create() method creates a new object, using an existing object as the prototype of the newly created object.

let Person = {
  age : 21,
  getIntro: function () {
    console.log(`Hey Guys, Myself ${this.name}. I am ${this.age} years old!`);
  }
};
let personObj1 = Object.create(Person);
personObj1.name = "Full Stack Tutorials"; // "name" is a property set only on "personObj", not on the "Person".
personObj1.age = 25; // inherited properties can be overwritten
personObj1.getIntro();

let personObj2 = Object.create(Person);
personObj2.getIntro();

//Output 
Hey Guys, Myself Full Stack Tutorials. I am 25 years old!
Hey Guys, Myself undefined. I am 21 years old!
var person1 = new Object();
person1.name = "Full Stack Tutorials",
person1.getName = function(){
  return this.name ; 
};

var person2 = new Object();
person2.name = "Full Stack Tutorials",
person2.age = 25,
person2.getName = function(){
  return this.name ; 
};

console.log(person1);
console.log(person2);

//Output
{name: "Full Stack Tutorials", getName: ƒ}
{name: "Full Stack Tutorials", age: 25, getName: ƒ}
Q:- How can we compare two Array/Objects in JavaScript. Explain?
Primitives data types like strings and numbers are compared by their value, while objects like arrays, dates, and plain objects are compared by their reference.

The comparison by reference basically checks to see if the objects given refer to the same location in memory.

var a = {};
var b = {};
var c = a;
console.log(a==b);	//false
console.log(a===b);	//false
console.log(a==c);	//true
console.log(a===c);	//true
Q:- What is a Closure in JavaScript?

A closure is a feature in JavaScript where an inner function has access to the outer (enclosing) function's variables.

  • It has access to it's own scope i.e. variables defined between its curly brackets.
  • It has access to the outer function's variables.
  • It has access to the global variables.
function outer() {
   var a = 10;
   function inner() {
         var b = 20; 
         console.log(a+b);
    }
   return inner;
}
Q:- Write the output of the following javascript programs?
for (var i = 0; i < 5; i++) {
  setTimeout(() => { 
	console.log(i); 
  }, 1000);
}

//Output
(5) 5

Reason: It will reference the last value stored in i, which was 5.

There are two solution to resolve this problem

  1. Closure
  2. let

Closure It creates a unique scope for each iteration, storing each unique value of the variable within it's scope.

for (var i = 0; i < 5; i++) {
    (function(x) {
        setTimeout(() => { 
			console.log(x); 
		}, 1000);
    })(i);
}
//Output
0
1
2
3
4
for (let i = 0; i < 5; i++) {
  setTimeout(() => { 
	console.log(i); 
  }, 1000);
}

//Output
0
1
2
3
4

Reason: let has block level scope so variable i is only seen in the for loop's block scope.

Q:- What is Callback Functions?

A callback function is a function passed into another function as an argument(let’s call this other function "otherFunction"), and the callback function gets executed inside the otherFunction after the function has finished execution.

function doHomeWork(subject, callback) {
  alert(`Starting my ${subject} homework.`);
  callback();
}
function alertFinished(){
  alert('Finished my homework');
}
doHomeWork('Computer Science', alertFinished);
Q:- Why do we need Callbacks?

JavaScript is an event driven language. This means that instead of waiting for a response before moving on, JavaScript will keep executing while listening for other events.

Callbacks are a way to make sure certain code doesn't execute until other code has already finished execution.

You may also like - Node.js Interview Questions and Answers
Q:- What is Prototype?

In JavaScript, objects have a special hidden property [[Prototype]] (as named in the specification), that is either null or references another object. That object is called "Prototype".

Q:- What is Prototypal Inheritance?

That [[Prototype]] has a "magical" meaning. When we want to read a property from object, and it’s missing, JavaScript automatically takes it from the prototype. In programming, such thing is called "prototypal inheritance"

The property [[Prototype]] is internal and hidden, but there are many ways to set it. via __proto__or Object.getPrototypeOf // old-way
obj.__proto__

// new-way
Object.getPrototypeOf(obj)

The __proto__ is considered outdated and somewhat deprecated (in browser-only part of the Javascript standard).

The modern methods are:
  • Object.create(proto[, descriptors]) – creates an empty object with given proto as [[Prototype]] and optional property descriptors.
  • Object.getPrototypeOf(obj) – returns the [[Prototype]] of obj.
  • Object.setPrototypeOf(obj, proto) – sets the [[Prototype]] of obj to proto.
var a = { name: "Full Stack Tutorials" };
a.__proto__ === Object.prototype // true
Object.getPrototypeOf(a) === Object.prototype // true

function Foo() {};
var b = new Foo();
b.__proto__ === Foo.prototype
b.__proto__.__proto__ === Object.prototype
Q:- What is the difference between classical and prototypal inheritance?

Classical Inheritance: A constructor function instantiates an instance via the new keyword. This new instance inherits properties from a parent class.

Prototypal Inheritance: An instance is created by cloning an existing object that serves as a prototype. This instance—often instantiated using a factory function or "Object.create()"—can benefit from selective inheritance from many different objects.

Q:- What is Promise in JavaScript?

A promise is an object which can be returned synchronously from an asynchronous function.

Promise overcome the problem of callback hell.
Promise States:
  • Fulfilled: onFulfilled() will be called (e.g. resolve() was called).
  • Rejected: onRejected() will be called (e.g. reject() was called).
  • Pending: initial state, neither fulfilled nor rejected.
Promise Consumers: then, catch, finally
var promise = new Promise(function(resolve, reject) { 
const A = "fullstacktutorials"; 
const B = "fullstacktutorials"
if(A === B) { 
	resolve(); 
} else { 
	reject(); 
} 
}); 

promise. 
	then(function () { 
		console.log('Success, Your promise has been resolved successfully'); 
	}). 
	catch(function () { 
		console.log('Something went wrong!'); 
	}); 
Example:- Write a function compareToTen that takes a number as an argument and returns a Promise that tests if the value is less than or greater than the value 10.
const compareToTen = (num) => {
  p = new Promise((resolve, reject) => {
    if(num > 10) {
      resolve(num + " is greater than 10, success!")
    } else {
      reject(num + " is less than 10, error!")
    }
  })
  return p
}

compareToTen(15)
  .then(result => console.log(result))
  .catch(error => console.log(error))
  
compareToTen(8)
  .then(result => console.log(result))
  .catch(error => console.log(error)) 
Q:- What is the difference between call and apply?
apply():

The apply() method calls a function with a given this value, and arguments provided as an array.

Syntax: fun.apply(thisArg, [argsArray])
call():

The call() method calls a function with a given this value and arguments provided individually

Syntax: fun.call(thisArg[, arg1[, arg2[, ...]]])
function myFunction(name, profession) {
    console.log("My name is " + name + " and I am a " + profession +".");
}
myFunction("John", "Developer");
myFunction.apply(this, ["Ajay", "Designer"]);
myFunction.call(this, "Ravi", "Blogger");

//Output:
My name is John and I am a Developer.
My name is Ajay and I am a Designer.
My name is Ravi and I am a Blogger.

A useful mnemonic is "A for array and C for comma."
bind():

bind allows you to set the this value now while allowing you to execute the function in the future, because it returns a new function object.

Syntax: fun.bind(thisArg[, arg1[, arg2[, ...]]])
Q:- What is the spread operator in JavaScript?

The spread operator (…) is a new operator introduced in ES6. It allows the expansion of an iterable (e.g., Array) into its constituent elements.

var childArr = [1, 2, 3];
var finalArr = [...childArr, 4, 5, 6];

console.log(finalArr); 
//Output:  [1, 2, 3, 4, 5, 6];
Q:- Remove the duplicate elements from the Array?
  1. Using ES6 - Spread & Set Operator
  2. Using jQuery each function
1. Using ES6 - Spread & Set Operator:
var numbers = [1, 2, 3, 4, 5, 5, 5, 5, 5, 5];

function removeDuplicates(array) {
  return [...new Set(array)];
}

console.log(removeDuplicates(numbers)); // [1, 2, 3, 4, 5]

Set was introduced in ES6: They can't have duplicate Items.

After we have done that, we simply convert the Set back to an array by using the spread operator.

2. Using jQuery each function:
var names = ["Mike","Matt","Nancy","Adam","Jenny","Nancy","Carl"];
var uniqueNames = [];
$.each(names, function(i, el){
	if($.inArray(el, uniqueNames) === -1) {
		uniqueNames.push(el);
	}
});
console.log(uniqueNames); // ["Mike", "Matt", "Nancy", "Adam", "Jenny", "Carl"]
Q:- What are the advantages of using JavaScript?

Following are the advantages of using JavaScript:

  1. Lightweight: JavaScript can be executed within the user’s browser without having to communicate with the server, saving on bandwidth.
  2. Speed: Client-side JavaScript is very fast because it can be run immediately within the client-side browser.
  3. Simplicity: JavaScript is relatively simple to learn and implement.
  4. Versatile: JavaScript supports multiple programming paradigms—object-oriented, imperative, and functional programming and can be used on both front-end and server-side technologies.
  5. Interactivity: Because tasks can be completed within the browser without communicating with the server, JavaScript can create a smooth "desktop-like" experience for the end user.
  6. Rich Interfaces: From drag-and-drop blocks to stylized sliders, there are numerous ways that JavaScript can be used to enhance a website’s UI/UX.
  7. Prototypal Inheritance: Objects can inherit from other objects, which makes JavaScript so simple, powerful, and great for dynamic applications.
  8. Platform Independent: JavaScript is platform independed language. Any JavaScript-enabled browser can understand and interpreted JavaScript code.
Q:- What is JavaScript Design Patterns?
Design patterns are advanced object-oriented solutions to commonly occurring software problems.
Creational Design Patterns:

As the name suggests, these patterns are for handling object creational mechanisms.

  1. Constructor pattern
  2. Factory pattern
  3. Prototype pattern
  4. Singleton pattern
Structural Design Patterns:

This pattern helps to obtain new functionalities without tampering with the existing ones.

  1. Adapter
  2. Bridge
  3. Composite
  4. Decorator
  5. Facade
  6. Flyweight
  7. Proxy
Behavioral Design Patterns:

These patterns are concerned with improving communication between dissimilar objects

  1. Iterator pattern
  2. Observer pattern
  3. Template pattern
  4. Strategy pattern
  5. State pattern
  6. Command pattern
Q:- Does JavaScript support Method Overloading?

No, JavaScript does not support overloading!. JavaScript supports overriding not overloading.

function getSum(n1, n2, n3) {
    return n1 + n2 + n3;
}
function getSum(n1, n2) {
    return n1 + n2;
}
var sum = getSum(2, 3, 10);
console.log(sum); // 5

If you will define two or more functions with the same name, the last one will override the previously defined functions and when a call will be made to the function, the last defined function will get executed.

Q:- Why typeof null return object in JavaScript?

Yes, it's true. since null is a primitive datatype still typeof null return object.

typeof null // "object" (not "null" for some legacy reasons)
Reason:
This is a kind of bug in javascript which can't be fixed.

In the inital release of JavaScript, values were represented as a combination of

  1. Tag Type
  2. Actual Value
tag refering for object and null was same, that's why typeof null return object.
Full Stack Tutorials

Author @FullStackTutorials | View all Articles