DailyDevDiet

logo - dailydevdiet

Learn. Build. Innovate. Elevate your coding skills with dailydevdiet!

30+ JavaScript Interview Questions and Answers

javascript interview questions

Introduction

JavaScript is one of the most popular programming languages in the world, powering web applications from front to back. Whether you’re a beginner looking for your first job or a seasoned developer aiming to level up, preparing for JavaScript interview questions is essential. This article covers the top JavaScript interview questions and answers that will help you showcase your knowledge and skills effectively. Let’s dive into the questions along with concise and clear answers.

1. What are Data Types in JavaScript?

JavaScript data types are mainly divided into two categories: primitive data types and non-primitive data types.

  1. Primitive Data Types:

Primitive Data Types also known as the in-built data types are the predefined data types provided by the JavaScript. Examples:

  • Numbers
  • Strings
  • Boolean
  • Symbol
  • Undefined
  • Null
  • BigInt
  1. Non-Primitive Data Types:

The data types derived from primitive data types are known as non-primitive data types or derived data types.

  • Objects
  • Functions
  • Arrays

2. Explain the difference between == and === in JavaScript?

The == (equality) and === (strict equality) operators are both used for comparison in JavaScript.

  • The == is the abstract equality operator, which performs type conversion before comparison.
  • The === is the abstract equality operator which does not perform type conversion, requiring both value and type to be the same.
console.log(10 == "10");       // true (convert string to number)
console.log(10 === "10")       // false (different data types)
console.log(0 == false)        // true (convert boolean to number)
console.log(0 === false)       // false (different data types)

3. What is the difference between null and undefined?

The null and undefined in JavaScript are two distinct types, but both represent the absence of a value.
null: Means a variable has been declared, but no value is assigned. The typeof returns “object” as type.
undefined: Is an assignment value and, it means a variable has been declared and given the value of null. The typeof returns “undefined” as type.

let nullVariable = null;
console.log(nullVariable)               // null
console.log(typeof nullVariable)        // “object”

let undefinedVar;
console.log(undefinedVar);              // undefined
console.log(typeof undefinedVar);       // “undefined”

4. Explain the concept of hoisting in JavaScript.

Hoisting in JavaScript is a behavior where variables and function declarations are moved to the top of their respective scope during compilation phase before execution. This means variables and functions can be used before they’re declared, although let and const variables are not initialized.
Example:

console.log(x);         // Output: undefined
var x = 50;
console.log(x);         // Output: 50

// The above code is interpreted by JavaScript as:
var x;
console.log(x);
x = 5;
console.log(x);

5. What is the difference between let, const and var?

var: Function-scoped (accessible throughout the function they are declared in) or globally-scoped and hoisted. Can be redeclared and updated, and initialized with undefined.

let: Block-scoped (not accessible to the entire function), not hoisted, can be reassigned.const: Block-scoped, not hoisted, and cannot be reassigned.

const: Block-scoped, not hoisted, and cannot be reassigned.

Use of let and const instead of var can help prevent unexpected scope problems and create more predictable, maintainable code.

6. Explain the concept of “scope” in JavaScript.

Scope in JavaScript refers to the context in which a variable is declared and can be accessed. In JavaScript, there are three types of scope:

1. Global Scope: Variables declared outside any function or block are Global variables.

2. Local Scope: Variables declared inside a block are called Local Variables.

3. Function Scope: Variables declared inside the current function.

7. What is variable shadowing?

Variable shadowing occurs when a variable declared in certain scope has the same name as a variable in an outer scope. The inner variable “shadows” the outer one, effectively hiding it.

let x = 5;
function exampleFunc(){
	let x = 15;			          // This x shadows the outer x
	console.log(x)			      // 20
	if(true) {
		let x = 25;		          // This x shadows both outer x variables
		console.log(x)		      // 25
}
console.log(x)			        // 15
}
exampleFunc();
console.log(x);				      // 5

8. What is closure in JavaScript?

A closure in JavaScript is a function that has access to variables in its outer (enclosing) lexical scope, even after the outer function has completed execution. This allows for data encapsulation.
Example:

// Outer function that creates a closure
Function Greeter(greeting){
	// This variable is enclosed in the closure
	let count = 0;
	// Inner function that forms a closure
	return function(name){
		// Accessing the enclosed variables (greeting and count)
		count++;
		console.log(`${greeting}, ${name}! This greeting has been used ${count} time(s).`);
};

}
const casualGreeter = Greeter(“Hello”);
const formalGreeter = Greeter(“Good Morning”);

// Using the greeter function
casualGreeter("John");
// Output: Hello, John! This greeting has been used 1 time(s).
casualGreeter("Marry");
// Output: Hello, Marry! This greeting has been used 2 time(s).

formatGreeter("Williams");
// Output: Good Morning, Williams! This greeting has been used 1 time(s).
casualGreeter("Christine");
// Output: Hello, Christine! This greeting has been used 2 time(s).

9. What is a Higher-Order Function?

A higher-order function in JavaScript is a function that treats other functions as data, either by taking them as arguments or returning them.
Example:

// Higher-order function that takes function as an argument
function operate(x,y, operation){
	return operation(x,y);		            // Calling the function with x and y
}

// Function to be passed as arguments
const add = (a,b) => a + b;
const multiply = (a,b) => a * b;

// Using the higher-order function
console.log(10,20, add);			          // Output: 30 (10 + 20)
console.log(10, 20, multiply)			      // Output: 200 (10 * 20)

// Higher-order function that return a function
Function createMultiplier(factor) {
	return function (number) {
		return number * factor;	            // Return a functions that multiplies by factor
}
}
const double = createMultiplier(2);
console.log(double(5));			            // Output: 10 (5 * 2)

10. What is an Immediately Invoked Function Expression (IIFE)?

An IIFE is a function that runs as soon as it is defined. It is often used to create private scopes and avoid polluting the global scope.

Syntax:
(function() { /* code */ })();
Example:

(function () {
	let privateVar = "I’m a private variable";
	console.log("IIFE is Running!");
	console.log(privateVar);
}(();

// IIFE with parameters
(function (name){
	console.log(`Hello, ${name}!`);
}((“John”);

// IIFE Arrow Function
(() => {
	console.log("IIFE Arrow Function");
})();

11. What are Arrow Function?

Arrow functions (also known as “fat arrow” functions) provide a shorter syntax for function expressions and do not have their own this, making them well-suited for callbacks.
Example:

const greet = () => {
    console.log( "Hi everyone!" );
}

12. What is the “this” keyword in JavaScript?

this refers to the context in which a function is invoked. In a global context, this refers to the window object, whereas in object methods, it refers to the object itself.
Example:

// In a method
let person = {
	name: "Bob";
	greet(){
		console.log(`Hi, My name is ${this.name}`);
}
}
person.greet();		// “Hi, My name is Bob”

// In an arrow function
let greet = () => {
	console.log(`Hello, ${this.name}`);
}

13. What is currying in JavaScript?

Currying is a technique where a function with multiple arguments is converted into a series of functions, each taking a single argument. This technique is named after Haskell Curry (an American mathematician) who developed this technique.

// Regular function
function normalFunction(param1, param2, param3) {
	return param1 + param2 + param3;
}

// Curried function
function curriedFunction(param1) {
	return function(param2) {
    	return function(param3) {
        	return param1 + param2 + param3;
    	};
	};
}

14. Explain the difference between global and local variables.

Global Variables: Variables declared outside any function or block are called Global Variables. Global variables are accessible from anywhere in the code, including inside functions. They have global scope.

Local Variables: Variables declared inside a function or block are called Local Variables. Local variables are accessible only within that function or block. They have local scope.

let globalVar = "I'm Global Variable";
function sampleFunction(){
	let localVar = "I'm Local Variable";
	console.log(globalVar)		  // Accessible - Output: I'm Global Variable
	console.log(localVar)		    // Accessible - Output: I'm Local Variable
}

sampleFunction();
console.log(globalVar)		    // Accessible - Output: I'm Global Variable
console.log(localVar)		    // ReferenceError- localVar is not defined.

15. What is the Temporal Dead Zone (TDZ) in JavaScript?

The Temporal Dead Zone (TDZ) is the period between entering a scope and the point where a variable is declared and initialized. It applies to the variables declared with let and const keywords. It helps catch errors by preventing access to variables before they are declared.

console.log(x);
// ReferenceError: Cannot access 'x' before initialization
let x = 5;
function sampleFunction(){
	console.log(y);
	// ReferenceError: Cannot access 'y' before initialization
	let y = 10;
}

sampleFunction();

16. Explain shallow vs. deep copy in JavaScript.

  • Shallow copy creates a copy of an object but copies only references for nested objects.
  • Deep copy creates a full copy of an object, including nested objects.

17. What is memoization in JavaScript?

Memoization is an optimization technique where function results are cached based on arguments, improving performance by avoiding redundant calculations.

18. Explain the concept of event delegation.

Event delegation allows a single event listener to handle events for multiple elements, improving performance. It leverages event bubbling, where events propagate up to a common ancestor that handles them.

19. Explain the typeof operator in JavaScript.

The typeof operator returns a string indicating the type of the operand, such as “string,” “number,” “object,” or “undefined.”

20. What are template literals in JavaScript?

Template literals, enclosed by backticks (`), allow for multi-line strings and embedded expressions using ${}.

21. What is the Intl object in JavaScript?

The Intl object is used for internationalization, providing methods for number formatting, date formatting, and collation in different locales.

22. What is the purpose of Symbol in JavaScript?

A Symbol is a unique and immutable primitive value often used to add unique property keys to objects, avoiding conflicts.

23. What is the Proxy object in JavaScript?

A Proxy is an object that allows you to customize fundamental operations on another object, like reading, writing, or deleting properties.

24. What is the difference between for...of and for...in loops?

  • for...of is used to iterate over iterable objects like arrays, strings, and maps, returning the values.
  • for...in is used to iterate over the keys of an object.

25. What is destructuring in JavaScript?

Destructuring is a syntax for unpacking values from arrays or properties from objects into distinct variables. For example: const [a, b] = [1, 2];

26. Explain map(), filter(), and reduce() in JavaScript.

  • map(): Creates a new array by applying a function to each element.
  • filter(): Creates a new array with elements that pass a test.
  • reduce(): Reduces an array to a single value based on a function.

Learn more about 10 Essential JavaScript Array Functions Every Developer Should Know

27. What is the difference between call(), apply(), and bind()?

  • call(): Invokes a function with a specific this and arguments.
  • apply(): Similar to call(), but takes an array of arguments.
  • bind(): Returns a new function with a fixed this value.

28. How does try...catch work in JavaScript?

try...catch handles exceptions. Code within try is executed, and if an error occurs, control is transferred to the catch block.

29. What is functional programming in JavaScript?

Functional programming is a paradigm where functions are treated as first-class citizens, and operations avoid changing state or mutable data.

30. What is the difference between synchronous and asynchronous code?

  • Synchronous code runs sequentially, blocking the execution of the next line until the current task completes.
  • Asynchronous code allows tasks to run in parallel, enabling the program to continue execution while waiting for other tasks to finish, often using callbacks, Promises, or async/await.

31. What is the difference between sessionStorage and localStorage?

  • sessionStorage stores data for the duration of a page session.
  • localStorage persists data even after the browser is closed.

32. How does the call stack work in JavaScript?

The call stack is a LIFO data structure that stores function calls. When a function is called, it’s pushed to the stack; when it returns, it’s popped from the stack.

Conclusion

These top JavaScript interview questions cover fundamental and advanced concepts, helping you feel prepared and confident for your JavaScript interview. Mastering these questions can give you a competitive edge, whether you’re a beginner or an experienced developer.

JavaScript continues to evolve, so staying updated on best practices and new features will help you excel as a JavaScript professional. Happy coding, and good luck with your interview!

Scroll to Top