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

Advanced 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.
Q:- What is the difference between let and var?

The difference is Scoping.

let gives you the privilege to declare variables that are limited in scope to the block, statement of expression unlike var.

var is rather a keyword which defines a variable globally regardless of block scope.

They are very similar when used like this outside a function block.

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

However, global variables defined with let will not be added as properties on the global window object like those defined with var.

console.log(window.x); // undefined
console.log(window.y); // 'Advanced JavaScript'
Following are key points

Global window object:Even if the let variable is defined as same as var variable globally, the let variable will not be added to the global window object. The similarities are alike when both are used outside the function block.

Block: let variables are usually used when there is a limited use of those variables. Say, in for loops, while loops or inside the scope of if conditions etc. Basically, where ever the scope of the variable has to be limited.

Redeclaration: let 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.

Function: let and var variables work the same way when used in a function block.

Q:- Explain Scoping in JavaScript?
  • The scope of variables determines where you can access them in your code.
  • Without taking ES6 modules into consideration, scope can be global or local. In modules, a third scope is the module scope.
  • Global scope consists of global variables and constants that can be accessed from anywhere in your code.
  • Local scope can be local to a function or a block.
  • Variables defined using var inside a function have function scope. These variables are accessible/visible inside the function they are defined in.
  • Variables and constants defined inside a block using let and const have block scope. They are accessible/visible inside the block they are defined in.
  • When var, let, or const are used in global or module scope, their scope is obviously going to be global or module.
  • Note: let & const can not be redeclared.
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 declared before it is being used.

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

JavaScript programming language is case sensitive.

Q:- What are the functions and it's type in JavaScript?

Anonymous function - This type of function has no name.

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

Named function - This function is named properly and specifically.

function myFunc(){
  alert("Advanced JavaScript Interview Questions and Answers");
}
myFunc();
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.
You may also like - React Js Interview Questions
Q:- What are the Objects in JavaScript?
  • A javaScript object is an entity having state and behavior (properties and method).
  • JavaScript is a prototype based language, so everything is an object.
var fullstacktutorials = {
	name: "JavaScript interview questions", 
	link: "https://www.fullstacktutorials.com", 
	description: "Advanced JavaScript Interview Questions and Answers for Experienced"
};
Q:- How many ways you can create an Object in javascript?

There is various way to define an object. It is totally based upon your requirement.

Below are the few styles Using:-

  1. Object Constructor
  2. Literal Constructor
  3. Function Based
  4. Protoype Based
  5. Function and Prototype Based
  6. Singleton Based

Examples:

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

Using Object.create() method:
var a = Object.create(null);
2. Literal constructor:
var person = { 
  name : "FullStackTutorials",
  getName : function (){
   return this.name
  } 
} 
3. Function constructor:
function Person(name){
  this.name = name
  this.getName = function(){
    return this.name
  } 
} 
4. Prototype:
function Person(){};
Person.prototype.name = "FullStackTutorials";

5. Function/Prototype combination:
function Person(name){
  this.name = name;
} 
Person.prototype.getName = function(){
  return this.name
} 
6. Singleton:
var person = new function(){
  this.name = "FullStackTutorials"
} 

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:- 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 and Prototypal Inheritance in JavaScript?
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".

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 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 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 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."
Q:- What is the spread operator in JavaScript?

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

const t = [1, 2, 3];

const s = [...t, 4, 5, 6];

console.log(s); 

//Output:  [1, 2, 3, 4, 5, 6];

Q:- Remove the duplicates from the following array?

Here’s a one-liner to remove duplicates from an array. (ES6, of course!)

const 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 and is similar to the Sets we encounter in Mathematics: They can’t have duplicates. After we have done that, we simply convert the Set back to an array by using the spread operator.

Another Soluntion:
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 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
Full Stack Tutorials

Author | Blogger @FullStackTutorials | View all articles