Skip to content

Javascript Interview Questions

JavaScript Interview Questions for Freshers

  1. What are the different data types present in JavaScript?
  2. Explain Hoisting in JavaScript.
  3. Why do we use the word debugger in JavaScript?
  4. Difference between == and === operators.
  5. Difference between var and let keyword in JavaScript.
  6. Explain Implicit Type Coercion in JavaScript.
  7. Is JavaScript a statically typed or a dynamically typed language?
  8. What is NaN property in JavaScript?
  9. Explain passed by value and passed by reference.
  10. What is an Immediately Invoked Function in JavaScript (IIFE)?
  11. What do you mean by strict mode in JavaScript and its characteristics?
  12. Explain Higher Order Functions in JavaScript.
  13. Explain this keyword.
  14. What do you mean by Self Invoking Functions?
  15. Explain call(), apply() and bind() methods.
  16. What is the difference between exec() and test() methods in JavaScript?
  17. What is currying in JavaScript?
  18. What are some advantages of using External JavaScript?
  19. Explain Scope and Scope Chain in JavaScript.
  20. Explain Closures in JavaScript.

JavaScript Interview Questions for Freshers (Continued)

  1. Mention some advantages of JavaScript.
  2. What are object prototypes?
  3. What are callbacks?
  4. What are the types of errors in JavaScript?
  5. What is memoization?
  6. What is recursion in a programming language?
  7. What is the use of a constructor function in JavaScript?
  8. What is DOM?
  9. Which method is used to retrieve a character from a certain index?
  10. What do you mean by BOM?
  11. What is the distinction between client-side and server-side JavaScript?

JavaScript Interview Questions for Experienced

  1. What are arrow functions?
  2. What do you mean by prototype design pattern?
  3. Differences between declaring variables using var, let, and const.
  4. What is the rest parameter and spread operator?
  5. In JavaScript, how many different methods can you make an object?
  6. What is the use of promises in JavaScript?
  7. What are classes in JavaScript?
  8. What are generator functions?
  9. Explain WeakSet in JavaScript.
  10. Why do we use callbacks?
  11. Explain WeakMap in JavaScript.
  12. What is Object Destructuring?
  13. Difference between prototypal and classical inheritance.
  14. What is a Temporal Dead Zone?
  15. What do you mean by JavaScript Design Patterns?
  16. Is JavaScript a pass-by-reference or pass-by-value language?
  17. Difference between async/await and Generators usage to achieve the same functionality.
  18. What are the primitive data types in JavaScript?
  19. What is the role of deferred scripts in JavaScript?
  20. What has to be done in order to put Lexical Scoping into practice?
  21. What is the purpose of the following JavaScript code?

JavaScript Coding Interview Questions

  1. Guess the outputs of the following code:
// Code 1:
function func1(){
setTimeout(()=>{
console.log(x);
console.log(y);
},3000);
var x = 2;
let y = 12;
}
func1();
// Code 2:
function func2(){
for(var i = 0; i < 3; i++){
setTimeout(()=> console.log(i),2000);
}
}
func2();
// Code 3:
(function(){
setTimeout(()=> console.log(1),2000);
console.log(2);
setTimeout(()=> console.log(3),0);
console.log(4);
})();
  1. Guess the outputs of the following code:
// Code 1:
let x= {}, y = {name:"Ronny"},z = {name:"John"};
x[y] = {name:"Vivek"};
x[z] = {name:"Akki"};
console.log(x[y]);
// Code 2:
function runFunc(){
console.log("1" + 1);
console.log("A" - 1);
console.log(2 + "-2" + "2");
console.log("Hello" - "World" + 78);
console.log("Hello"+ "78");
}
runFunc();
// Code 3:
let a = 0;
let b = false;
console.log((a == b));
console.log((a === b));
  1. Guess the output of the following code:
var x = 23;
(function(){
var x = 43;
(function random(){
x++;
console.log(x);
var x = 21;
})();
})();
  1. Guess the outputs of the following code:
// Code 1
let hero = {
powerLevel: 99,
getPower(){
return this.powerLevel;
}
}
let getPower = hero.getPower;
let hero2 = {powerLevel:42};
console.log(getPower());
console.log(getPower.apply(hero2));
// Code 2
const a = function(){
console.log(this);
const b = {
func1: function(){
console.log(this);
}
}
const c = {
func2: ()=>{
console.log(this);
}
}
b.func1();
c.func2();
}
a();
// Code 3
const b = {
name:"Vivek",
f: function(){
var self = this;
console.log(this.name);
(function(){
console.log(this.name);
console.log(self.name);
})();
}
}
b.f();
  1. Guess the outputs of the following code:
// Code 1
(function(a){
return (function(){
console.log(a);
a = 23;
})()
})(45);
// Code 2
// Each time bigFunc is called, an array of size 700 is being created,
// Modify the code so that we don't create the same array again and again
function bigFunc(element){
let newArray = new Array(700).fill('');
return newArray[element];
}
console.log(bigFunc(599)); // Array is created
console.log(bigFunc(670)); // Array is created again
// Code 3
// The following code outputs 2 and 2 after waiting for one second
// Modify the code to output 0 and 1 after one second.
function randomFunc(){
for(var i = 0; i < 2; i++){
setTimeout(()=> console.log(i),1000);
}
}
randomFunc();
  1. Write a function that performs binary search on a sorted array.
function binarySearch(arr,value,startPos,endPos){
if(startPos > endPos) return -1;
let middleIndex = Math.floor(startPos+endPos)/2;
if(arr[middleIndex] === value) return middleIndex;
elsif(arr[middleIndex > value]){
return binarySearch(arr,value,startPos,middleIndex-1);
}
else{
return binarySearch(arr,value,middleIndex+1,endPos);
}
}
  1. Implement a function that returns an updated array with r right rotations on an array of integers a.
Example:
Given the following array: [2,3,4,5,7]
Perform 3 right rotations:
First rotation : [7,2,3,4,5] , Second rotation : [5,7,2,3,4] and, Third rotation: [4,5,7,2,3]
return [4,5,7,2,3]
  1. Write the code for dynamically inserting new components.
  2. Write the code: If two strings are anagrams of one another, then return true.
  3. Write the code to find the vowels.
  4. In JavaScript, how do you turn an Object into an Array []?
  5. What is the output of the following code?
const b = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < 10; i++) {
setTimeout(() => console.log(b[i]), 1000);
}
for (var i = 0; i < 10; i++) {
setTimeout(() => console.log(b[i]), 1000);
}

Answers:

  1. What are the different data types present in JavaScript?
    • Primitive Data Types: String, Number, Boolean, Null, Undefined, Symbol, BigInt.
    • Non-Primitive Data Types: Object (including Arrays and Functions).
  2. Explain Hoisting in JavaScript.
    • Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compilation phase.
  3. Why do we use the word debugger in JavaScript?
    • The debugger statement is used to invoke any available debugging functionality, such as setting a breakpoint in the code.
  4. Difference between == and === operators.
    • == checks for value equality with type coercion, while === checks for both value and type equality without type coercion.
  5. Difference between var and let keyword in JavaScript.
    • var is function-scoped and can be redeclared, while let is block-scoped and cannot be redeclared in the same scope.
  6. Explain Implicit Type Coercion in JavaScript.
    • Implicit type coercion is when JavaScript automatically converts one data type to another during operations, such as adding a number to a string.
  7. Is JavaScript a statically typed or a dynamically typed language?
    • JavaScript is a dynamically typed language, meaning variable types are determined at runtime and can change.
  8. What is NaN property in JavaScript?
    • NaN stands for “Not-a-Number” and is a special value representing an undefined or unrepresentable numerical result.
  9. Explain passed by value and passed by reference.
    • Passed by value means a copy of the variable’s value is passed, while passed by reference means a reference to the variable’s memory location is passed.
  10. What is an Immediately Invoked Function in JavaScript (IIFE)?
    • An IIFE is a function that is defined and executed immediately after its creation, often used to create a private scope.
  11. What do you mean by strict mode in JavaScript and its characteristics?
    • Strict mode is a way to opt into a restricted variant of JavaScript, which helps catch common coding errors and prevents certain unsafe actions.
  12. Explain Higher Order Functions in JavaScript.
    • Higher Order Functions are functions that can take other functions as arguments or return functions as their result.
  13. Explain this keyword.
    • The this keyword refers to the object that is executing the current function, and its value depends on how the function is called.
  14. What do you mean by Self Invoking Functions?
    • Self Invoking Functions are functions that are executed immediately after they are defined, similar to IIFEs.
  15. Explain call(), apply() and bind() methods.
    • call() and apply() are used to invoke functions with a specified this context, while bind() returns a new function with a bound this context.
  16. What is the difference between exec() and test() methods in JavaScript?
    • exec() returns an array of matched results or null, while test() returns a boolean indicating whether a match was found.
  17. What is currying in JavaScript?
    • Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions that each take a single argument.
  18. What are some advantages of using External JavaScript?
    • External JavaScript allows for code reusability, better organization, and improved loading times through caching.
  19. Explain Scope and Scope Chain in JavaScript.
    • Scope refers to the accessibility of variables, while the scope chain is the hierarchy of scopes that determines variable resolution.
  20. Explain Closures in JavaScript.
    • Closures are functions that retain access to their lexical scope even when executed outside that scope.

Answers (Continued):

  1. Mention some advantages of JavaScript.
    • Client-side execution, versatility, rich interfaces, and ease of learning.
  2. What are object prototypes?
    • Prototypes are objects from which other objects inherit properties and methods in JavaScript.
  3. What are callbacks?
    • Callbacks are functions passed as arguments to other functions, to be executed after a certain operation is completed.
  4. What are the types of errors in JavaScript?
    • Syntax Errors, Runtime Errors, and Logical Errors.
  5. What is memoization?
    • Memoization is an optimization technique that stores the results of expensive function calls and returns the cached result when the same inputs occur again.
  6. What is recursion in a programming language?
    • Recursion is a programming technique where a function calls itself to solve a problem.
  7. What is the use of a constructor function in JavaScript?
    • Constructor functions are used to create multiple instances of an object with the same properties and methods.
  8. What is DOM?
    • The Document Object Model (DOM) is a programming interface for web documents that represents the page structure as a tree of objects.
  9. Which method is used to retrieve a character from a certain index?
    • The charAt() method is used to retrieve a character from a specified index in a string.
  10. What do you mean by BOM?
    • The Browser Object Model (BOM) provides methods and properties to interact with the browser window and its components.
  11. What is the distinction between client-side and server-side JavaScript?
    • Client-side JavaScript runs in the user’s browser, while server-side JavaScript runs on the server, typically using environments like Node.js.

Answers (Experienced):

  1. What are arrow functions?
    • Arrow functions are a concise syntax for writing functions in JavaScript, using the => syntax, and they do not have their own this context.
  2. What do you mean by prototype design pattern?
    • The prototype design pattern is a creational pattern that allows objects to be cloned from a prototype instance rather than creating new instances from scratch.
  3. Differences between declaring variables using var, let, and const.
    • var is function-scoped and can be redeclared; let is block-scoped and cannot be redeclared; const is block-scoped and must be initialized at declaration and cannot be reassigned.
  4. What is the rest parameter and spread operator?
    • The rest parameter (...args) allows a function to accept an indefinite number of arguments as an array, while the spread operator (...array) expands an array into individual elements.
  5. In JavaScript, how many different methods can you make an object?
    • Objects can be created using object literals, constructor functions, Object.create(), and ES6 classes.
  6. What is the use of promises in JavaScript?
    • Promises are used to handle asynchronous operations, providing a way to attach callbacks for success or failure of an operation.
  7. What are classes in JavaScript?
    • Classes are syntactical sugar over JavaScript’s existing prototype-based inheritance, providing a clearer syntax for creating objects and handling inheritance.
  8. What are generator functions?
    • Generator functions are functions that can be paused and resumed, using the function* syntax and the yield keyword.
  9. Explain WeakSet in JavaScript.
    • A WeakSet is a collection of objects where the references to the objects are weak, meaning they can be garbage collected if there are no other references to them.
  10. Why do we use callbacks?
    • Callbacks are used to handle asynchronous operations and to ensure that certain code is executed only after a specific task is completed.
  11. Explain WeakMap in JavaScript.
    • A WeakMap is a collection of key-value pairs where the keys are objects and the references to the keys are weak, allowing for garbage collection when there are no other references to the keys.
  12. What is Object Destructuring?
    • Object destructuring is a syntax that allows you to extract properties from an object and assign them to variables in a concise way.
  13. Difference between prototypal and classical inheritance.
    • Prototypal inheritance is based on objects inheriting directly from other objects, while classical inheritance is based on classes and instances.
  14. What is a Temporal Dead Zone?
    • The Temporal Dead Zone (TDZ) is the period between the entering of a block scope and the declaration of a variable using let or const, during which the variable cannot be accessed.
  15. What do you mean by JavaScript Design Patterns?
    • JavaScript Design Patterns are reusable solutions to common problems in software design, providing best practices for structuring code.
  16. Is JavaScript a pass-by-reference or pass-by-value language?
    • JavaScript is pass-by-value for primitive types and pass-by-reference for objects.
  17. Difference between async/await and Generators usage to achieve the same functionality.
    • async/await is a syntactic sugar over promises for handling asynchronous code, while generators use the yield keyword to pause and resume execution.
  18. What are the primitive data types in JavaScript?
    • String, Number, Boolean, Null, Undefined, Symbol, BigInt.
  19. What is the role of deferred scripts in JavaScript?
    • Deferred scripts are executed after the HTML document has been fully parsed, allowing for non-blocking loading of JavaScript files.
  20. What has to be done in order to put Lexical Scoping into practice?
    • Lexical scoping is implemented by defining functions within other functions, allowing inner functions to access variables from their outer functions.
  21. What is the purpose of the following JavaScript code?
    • (Please provide the specific code for analysis.)

Answers (Coding):

  1. Guess the outputs of the following code:
// Code 1 Output:
undefined
ReferenceError: y is not defined
// Code 2 Output:
3
3
3
// Code 3 Output:
2
4
3
1
  1. Guess the outputs of the following code:
// Code 1 Output:
{name: "Akki"}
// Code 2 Output:
11
NaN
2-22
NaN78
Hello78
// Code 3 Output:
true
false
  1. Guess the output of the following code:
Output:
NaN
  1. Guess the outputs of the following code:
// Code 1 Output:
undefined
42
// Code 2 Output:
{}
{}
// Code 3 Output:
Vivek
undefined
Vivek
  1. Guess the outputs of the following code:
// Code 1 Output:
45
// Code 2 Modified Code:
let bigArray = new Array(700).fill('');
function bigFunc(element){
return bigArray[element];
}
console.log(bigFunc(599)); // Array is created only once
console.log(bigFunc(670)); // Array is reused
// Code 3 Modified Code:
function randomFunc(){
for(let i = 0; i < 2; i++){
setTimeout(()=> console.log(i),1000);
}
}
randomFunc();
  1. Write a function that performs binary search on a sorted array.
function binarySearch(arr,value,startPos,endPos){
if(startPos > endPos) return -1;
let middleIndex = Math.floor((startPos+endPos)/2);
if(arr[middleIndex] === value) return middleIndex;
else if(arr[middleIndex] > value){
return binarySearch(arr,value,startPos,middleIndex-1);
}
else{
return binarySearch(arr,value,middleIndex+1,endPos);
}
}
  1. Implement a function that returns an updated array with r right rotations on an array of integers a.
function rightRotateArray(a, r) {
const n = a.length;
r = r % n; // In case r is greater than n
return a.slice(n - r).concat(a.slice(0, n - r));
}
// Example usage:
const arr = [2, 3, 4, 5, 7];
const rotations = 3;
const result = rightRotateArray(arr, rotations);
console.log(result); // Output: [4, 5, 7, 2, 3]
  1. Write the code for dynamically inserting new components.
function insertComponent(componentHTML, containerId) {
const container = document.getElementById(containerId);
if (container) {
container.innerHTML += componentHTML;
}
}
  1. Write the code: If two strings are anagrams of one another, then return true.
function areAnagrams(str1, str2) {
const normalize = str => str.toLowerCase().split('').sort().join('');
return normalize(str1) === normalize(str2);
}
  1. Write the code to find the vowels.
function findVowels(str) {
const vowels = 'aeiouAEIOU';
return str.split('').filter(char => vowels.includes(char));
}
  1. In JavaScript, how do you turn an Object into an Array []?
const obj = { a: 1, b: 2, c: 3 };
const arr = Object.values(obj); // [1, 2, 3]
  1. What is the output of the following code?
// Output:
10
undefined
10
undefined