Javascript Interview Questions
JavaScript Interview Questions for Freshers
- What are the different data types present in JavaScript?
- Explain Hoisting in JavaScript.
- Why do we use the word
debuggerin JavaScript? - Difference between
==and===operators. - Difference between
varandletkeyword in JavaScript. - Explain Implicit Type Coercion in JavaScript.
- Is JavaScript a statically typed or a dynamically typed language?
- What is
NaNproperty in JavaScript? - Explain passed by value and passed by reference.
- What is an Immediately Invoked Function in JavaScript (IIFE)?
- What do you mean by strict mode in JavaScript and its characteristics?
- Explain Higher Order Functions in JavaScript.
- Explain
thiskeyword. - What do you mean by Self Invoking Functions?
- Explain
call(),apply()andbind()methods. - What is the difference between
exec()andtest()methods in JavaScript? - What is currying in JavaScript?
- What are some advantages of using External JavaScript?
- Explain Scope and Scope Chain in JavaScript.
- Explain Closures in JavaScript.
JavaScript Interview Questions for Freshers (Continued)
- Mention some advantages of JavaScript.
- What are object prototypes?
- What are callbacks?
- What are the types of errors in JavaScript?
- What is memoization?
- What is recursion in a programming language?
- What is the use of a constructor function in JavaScript?
- What is DOM?
- Which method is used to retrieve a character from a certain index?
- What do you mean by BOM?
- What is the distinction between client-side and server-side JavaScript?
JavaScript Interview Questions for Experienced
- What are arrow functions?
- What do you mean by prototype design pattern?
- Differences between declaring variables using
var,let, andconst. - What is the rest parameter and spread operator?
- In JavaScript, how many different methods can you make an object?
- What is the use of promises in JavaScript?
- What are classes in JavaScript?
- What are generator functions?
- Explain
WeakSetin JavaScript. - Why do we use callbacks?
- Explain
WeakMapin JavaScript. - What is Object Destructuring?
- Difference between prototypal and classical inheritance.
- What is a Temporal Dead Zone?
- What do you mean by JavaScript Design Patterns?
- Is JavaScript a pass-by-reference or pass-by-value language?
- Difference between
async/awaitand Generators usage to achieve the same functionality. - What are the primitive data types in JavaScript?
- What is the role of deferred scripts in JavaScript?
- What has to be done in order to put Lexical Scoping into practice?
- What is the purpose of the following JavaScript code?
JavaScript Coding Interview Questions
- 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);})();- 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));- Guess the output of the following code:
var x = 23;(function(){var x = 43;(function random(){x++;console.log(x);var x = 21;})();})();- Guess the outputs of the following code:
// Code 1let hero = {powerLevel: 99,getPower(){return this.powerLevel;}}let getPower = hero.getPower;let hero2 = {powerLevel:42};console.log(getPower());console.log(getPower.apply(hero2));// Code 2const a = function(){console.log(this);const b = {func1: function(){console.log(this);}}const c = {func2: ()=>{console.log(this);}}b.func1();c.func2();}a();// Code 3const b = {name:"Vivek",f: function(){var self = this;console.log(this.name);(function(){console.log(this.name);console.log(self.name);})();}}b.f();- 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 againfunction bigFunc(element){let newArray = new Array(700).fill('♥');return newArray[element];}console.log(bigFunc(599)); // Array is createdconsole.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();- 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);}}- Implement a function that returns an updated array with
rright rotations on an array of integersa.
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]- Write the code for dynamically inserting new components.
- Write the code: If two strings are anagrams of one another, then return
true. - Write the code to find the vowels.
- In JavaScript, how do you turn an Object into an Array
[]? - 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:
- 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).
- 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.
- Why do we use the word
debuggerin JavaScript?
- The
debuggerstatement is used to invoke any available debugging functionality, such as setting a breakpoint in the code.
- The
- Difference between
==and===operators.
==checks for value equality with type coercion, while===checks for both value and type equality without type coercion.
- Difference between
varandletkeyword in JavaScript.
varis function-scoped and can be redeclared, whileletis block-scoped and cannot be redeclared in the same scope.
- 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.
- 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.
- What is
NaNproperty in JavaScript?
NaNstands for “Not-a-Number” and is a special value representing an undefined or unrepresentable numerical result.
- 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.
- 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.
- 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.
- Explain Higher Order Functions in JavaScript.
- Higher Order Functions are functions that can take other functions as arguments or return functions as their result.
- Explain
thiskeyword.
- The
thiskeyword refers to the object that is executing the current function, and its value depends on how the function is called.
- The
- What do you mean by Self Invoking Functions?
- Self Invoking Functions are functions that are executed immediately after they are defined, similar to IIFEs.
- Explain
call(),apply()andbind()methods.
call()andapply()are used to invoke functions with a specifiedthiscontext, whilebind()returns a new function with a boundthiscontext.
- What is the difference between
exec()andtest()methods in JavaScript?
exec()returns an array of matched results or null, whiletest()returns a boolean indicating whether a match was found.
- 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.
- What are some advantages of using External JavaScript?
- External JavaScript allows for code reusability, better organization, and improved loading times through caching.
- 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.
- Explain Closures in JavaScript.
- Closures are functions that retain access to their lexical scope even when executed outside that scope.
Answers (Continued):
- Mention some advantages of JavaScript.
- Client-side execution, versatility, rich interfaces, and ease of learning.
- What are object prototypes?
- Prototypes are objects from which other objects inherit properties and methods in JavaScript.
- What are callbacks?
- Callbacks are functions passed as arguments to other functions, to be executed after a certain operation is completed.
- What are the types of errors in JavaScript?
- Syntax Errors, Runtime Errors, and Logical Errors.
- 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.
- What is recursion in a programming language?
- Recursion is a programming technique where a function calls itself to solve a problem.
- 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.
- 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.
- 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.
- The
- What do you mean by BOM?
- The Browser Object Model (BOM) provides methods and properties to interact with the browser window and its components.
- 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):
- What are arrow functions?
- Arrow functions are a concise syntax for writing functions in JavaScript, using the
=>syntax, and they do not have their ownthiscontext.
- Arrow functions are a concise syntax for writing functions in JavaScript, using the
- 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.
- Differences between declaring variables using
var,let, andconst.
varis function-scoped and can be redeclared;letis block-scoped and cannot be redeclared;constis block-scoped and must be initialized at declaration and cannot be reassigned.
- 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.
- The rest parameter (
- 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.
- Objects can be created using object literals, constructor functions,
- 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.
- 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.
- What are generator functions?
- Generator functions are functions that can be paused and resumed, using the
function*syntax and theyieldkeyword.
- Generator functions are functions that can be paused and resumed, using the
- Explain
WeakSetin JavaScript.
- A
WeakSetis 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.
- A
- 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.
- Explain
WeakMapin JavaScript.
- A
WeakMapis 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.
- A
- 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.
- 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.
- 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
letorconst, during which the variable cannot be accessed.
- The Temporal Dead Zone (TDZ) is the period between the entering of a block scope and the declaration of a variable using
- 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.
- 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.
- Difference between
async/awaitand Generators usage to achieve the same functionality.
async/awaitis a syntactic sugar over promises for handling asynchronous code, while generators use theyieldkeyword to pause and resume execution.
- What are the primitive data types in JavaScript?
- String, Number, Boolean, Null, Undefined, Symbol, BigInt.
- 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.
- 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.
- What is the purpose of the following JavaScript code?
- (Please provide the specific code for analysis.)
Answers (Coding):
- Guess the outputs of the following code:
// Code 1 Output:undefinedReferenceError: y is not defined// Code 2 Output:333// Code 3 Output:2431- Guess the outputs of the following code:
// Code 1 Output:{name: "Akki"}// Code 2 Output:11NaN2-22NaN78Hello78// Code 3 Output:truefalse- Guess the output of the following code:
Output:NaN- Guess the outputs of the following code:
// Code 1 Output:undefined42// Code 2 Output:{}{}// Code 3 Output:VivekundefinedVivek- 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 onceconsole.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();- 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);}}- Implement a function that returns an updated array with
rright rotations on an array of integersa.
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]- Write the code for dynamically inserting new components.
function insertComponent(componentHTML, containerId) { const container = document.getElementById(containerId); if (container) { container.innerHTML += componentHTML; }}- 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);}- Write the code to find the vowels.
function findVowels(str) { const vowels = 'aeiouAEIOU'; return str.split('').filter(char => vowels.includes(char));}- 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]- What is the output of the following code?
// Output:10undefined10undefined