Master JavaScript Interviews with Top 25+ Q&A | Try Personalized AI Help

Join our community to see how developers are using Workik AI everyday.

Top 20+ Interview Question & Answers for JavaScript Developers

Q1: What is the difference between let, const, and var in JavaScript?

var: Declares a variable, optionally initializing it to a value. It is function-scoped and can be re-declared and updated.

let: Declares a block-scoped local variable, optionally initializing it to a value. It cannot be re-declared but can be updated.

const: Declares a block-scoped, read-only named constant. The value must be initialized during declaration and cannot be reassigned.

var x = 1; // function-scoped
let y = 2; // block-scoped
const z = 3; // block-scoped and constant

Q2: Explain the concept of closures in JavaScript.

A closure is a function that has access to its own scope, the scope of the outer function, and the global scope. It remembers the environment in which it was created.

function outerFunction() {
    let outerVariable = 'I am outside!';

    function innerFunction() {
        console.log(outerVariable); // Can access outerVariable
    }

    return innerFunction;
}

const closure = outerFunction();
closure(); // Logs 'I am outside!'

Q3: What is hoisting in JavaScript?

Hoisting is JavaScript's default behavior of moving declarations to the top of the current scope (global or function scope). This means that variable and function declarations can be used before they are declared.

console.log(a); // undefined due to hoisting
var a = 5;

console.log(b); // ReferenceError: Cannot access 'b' before initialization
let b = 5;

Q4: Describe the Event Loop in JavaScript.

The Event Loop is a mechanism that handles asynchronous operations in JavaScript. It continuously checks the call stack and the task queue. When the call stack is empty, it takes the first task from the queue and pushes it onto the call stack, executing it.

Components:

  • Call Stack: Executes function calls.
  • Task Queue: Stores asynchronous callbacks (e.g., setTimeout).
  • Event Loop: Moves tasks from the task queue to the call stack when the call stack is empty.

Q5: What are Promises, and how do they work in JavaScript?

Promises are objects representing the eventual completion or failure of an asynchronous operation. They can be in one of three states: pending, fulfilled , or rejected.

let promise = new Promise((resolve, reject) => {
    // Asynchronous operation
    let success = true; // Simulate success or failure
    if (success) {
        resolve('Operation was successful');
    } else {
        reject('Operation failed');
    }
});

promise.then((message) => {
    console.log(message); // 'Operation was successful'
}).catch((error) => {
    console.error(error);
});

Request question

Please fill in the form below to submit your question.

Q6: What is the difference between == and === in JavaScript?

== (Abstract Equality): Compares two values for equality, performing type conversion if necessary.

=== (Strict Equality): Compares two values for equality without performing type conversion. Both the value and the type must be the same.

console.log(5 == '5'); // true (type conversion happens)
console.log(5 === '5'); // false (no type conversion)

Q7: Explain the concept of Prototypal Inheritance in JavaScript.

Prototypal Inheritance is a feature in JavaScript where objects can inherit properties and methods from other objects. Each object has a private property (prototype) that holds a link to another object called its prototype. This chain of prototypes is known as the prototype chain.

const animal = {
    eat: function() {
        console.log('Eating...');
    }
};

const dog = Object.create(animal);
dog.bark = function() {
    console.log('Barking...');
};

dog.eat(); // Eating... (inherited from animal)
dog.bark(); // Barking...

Q8: What is a Higher-Order Function in JavaScript?

A Higher-Order Function is a function that can take other functions as arguments and/or return functions as its result. These are used extensively in functional programming.

function higherOrderFunction(callback) {
    return function(x) {
        return callback(x);
    };
}

const double = higherOrderFunction(function(x) {
    return x * 2;
});

console.log(double(5)); // 10

Q9: What is the this keyword, and how is it used in JavaScript?

The this keyword refers to the object it belongs to. Its value is determined by how a function is called:

  • Global Scope: In the global scope, this refers to the global object (window in browsers).
  • Method: In a method, this refers to the object that owns the method.
  • Constructor: In a constructor, this refers to the newly created instance.
function showThis() {
    console.log(this);
}

const obj = {
    method: showThis
};

showThis(); // Window (or global object in Node.js)
obj.method(); // obj

Q10: What is the difference between synchronous and asynchronous code in JavaScript?

Synchronous Code: Executes sequentially, blocking further execution until the current operation completes.

Asynchronous Code: Executes independently of the main program flow, allowing other operations to run while waiting for an asynchronous operation to complete.

// Synchronous
console.log('Start');
console.log('End');

// Asynchronous
console.log('Start');
setTimeout(() => {
    console.log('Middle');
}, 1000);
console.log('End');

Request question

Please fill in the form below to submit your question.

Q11: What are arrow functions, and how do they differ from regular functions in JavaScript?

Arrow functions are a shorthand syntax for writing function expressions in JavaScript. They differ from regular functions in several key ways:

  • Syntax: Arrow functions are more concise.
  • this Binding: Arrow functions do not have their own this context; they inherit this from the enclosing scope.
  • arguments Object: Arrow functions do not have their own arguments object.
// Regular function
function regularFunction(a, b) {
    return a + b;
}

// Arrow function
const arrowFunction = (a, b) => a + b;

Q12: What is the difference between null and undefined in JavaScript?

null : Represents the intentional absence of any object value. It is an assignment value that indicates a variable points to no object.

undefined : Indicates that a variable has been declared but has not yet been assigned a value.

Q13: Explain the concept of currying in JavaScript.

Currying is a technique of transforming a function that takes multiple arguments into a sequence of functions, each taking a single argument. This allows partial application of a function's arguments.

function curryFunction(a) {
    return function(b) {
        return function(c) {
            return a + b + c;
        };
    };
}

const curried = curryFunction(1)(2)(3); // 6

Q14: What is event delegation in JavaScript?

Event delegation is a technique where a single event listener is added to a parent element to manage events for its child elements. This is useful for handling events efficiently when dealing with many child elements.

Q15: What are JavaScript promises, and why are they useful?

Promises are objects representing the eventual completion or failure of an asynchronous operation. They are useful for managing asynchronous code in a more readable and maintainable way compared to callbacks, avoiding callback hell.

let promise = new Promise((resolve, reject) => {
    // asynchronous operation
    let success = true;
    if (success) {
        resolve('Operation was successful');
    } else {
        reject('Operation failed');
    }
});

promise
    .then((message) => console.log(message))
    .catch((error) => console.error(error));

Request question

Please fill in the form below to submit your question.

Q16: What are the main differences between forEach , map , and filter methods in JavaScript?

  • forEach : Iterates over array elements, executing a provided function once for each element. It does not return a new array.
  • map : Iterates over array elements, executing a provided function for each element and returning a new array with the results.
  • filter : Iterates over array elements, executing a provided function for each element, and returns a new array containing only the elements that pass the test implemented by the function.

Q17: Explain the concept of async and await in JavaScript.

async and await are syntactic sugar for working with Promises, making asynchronous code look and behave more like synchronous code.

  • async : Declares an asynchronous function, which implicitly returns a Promise.
  • await : Pauses the execution of an async function until the Promise is resolved, returning the resolved value.
async function fetchData() {
    try {
        const response = await fetch('https://api.example.com/data');
        const data = await response.json();
        console.log(data);
    } catch (error) {
        console.error('Error fetching data:', error);
    }
}

fetchData();

Q18: What is the bind method in JavaScript, and how is it used?

The bind method creates a new function that, when called, has its this keyword set to the provided value, with a given sequence of arguments preceding any provided when the new function is called.

const person = {
    name: 'John',
    greet: function(greeting) {
        console.log(greeting + ', ' + this.name);
    }
};

const greetJohn = person.greet.bind(person, 'Hello');
greetJohn(); // Hello, John

Q19: Explain the concept of debouncing and throttling in JavaScript.

Debouncing: Ensures that a function is not called again until a certain amount of time has passed since it was last called. Useful for limiting the rate at which a function is executed.

function debounce(func, wait) {
    let timeout;
    return function() {
        clearTimeout(timeout);
        timeout = setTimeout(() => func.apply(this, arguments), wait);
    };
}

Throttling: Ensures that a function is called at most once in a specified time period. Useful for controlling the execution rate of an event handler.

function throttle(func, limit) {
    let lastFunc;
    let lastRan;
    return function() {
        const context = this;
        const args = arguments;
        if (!lastRan) {
            func.apply(context, args);
            lastRan = Date.now();
        } else {
            clearTimeout(lastFunc);
            lastFunc = setTimeout(() => {
                if ((Date.now() - lastRan) >= limit) {
                    func.apply(context, args);
                    lastRan = Date.now();
                }
            }, limit - (Date.now() - lastRan));
        }
    };
}

Q20: What is the event loop, and why is it important in JavaScript?

The event loop is a fundamental part of JavaScript's concurrency model. It allows JavaScript to perform non-blocking operations by offloading operations to the browser (or Node.js) and running a loop that checks for tasks, executes them, and then waits for more tasks.

  • Call Stack: Executes code, one frame at a time.
  • Web APIs: Browser features like DOM, setTimeout, etc.
  • Callback Queue: Queues asynchronous callbacks to be executed.
  • Event Loop: Continuously checks if the call stack is empty and moves the first task from the callback queue to the call stack for execution.

Request question

Please fill in the form below to submit your question.

Prepare with 10 Hands-On JavaScript Interview Q&A

Q1: The following code is intended to sum all elements in an array, but it contains an error. Identify and fix the error.
(Basic)
function sumArray(arr) {
    let sum = 0;
    for (let i = 0; i <= arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}

console.log(sumArray([1, 2, 3, 4])); // Expected output: 10

         

The loop should iterate until i < arr.length instead of i <= arr.length .

function sumArray(arr) {
    let sum = 0;
    for (let i = 0; i < arr.length; i++) {
        sum += arr[i];
    }
    return sum;
}

console.log(sumArray([1, 2, 3, 4])); // Output: 10
Q2: The following code calculates the factorial of a number using recursion. Optimize it to avoid stack overflow for large input values.
(Intermediate)function factorial(n) {
    if (n === 0) {
        return 1;
    }
    return n * factorial(n - 1);
}

console.log(factorial(5)); // Expected output: 120

Use an iterative approach to avoid stack overflow.

function factorial(n) {
    let result = 1;
    for (let i = 1; i <= n; i++) {
        result *= i;
    }
    return result;
}

console.log(factorial(5)); // Output: 120
Q3: The following code finds the largest number in an array. Improve its performance.
(Basic)
function findLargest(arr) {
    let largest = -Infinity;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            largest = arr[i];
        }
    }
    return largest;
}

console.log(findLargest([1, 2, 3, 4, 5])); // Expected output: 5

Use the Math.max method combined with the spread operator for better performance and readability.

function findLargest(arr) {
    return Math.max(...arr);
}

console.log(findLargest([1, 2, 3, 4, 5])); // Output: 5
Q4: Write a function that takes a string and returns a new string with the characters in reverse order.
(Basic)
function reverseString(str) {
    return str.split('').reverse().join('');
}

console.log(reverseString('hello')); // Output: 'olleh'
Q5: What will be the output of the following code snippet?
(Medium)
var a = 10;

function foo() {
    console.log(a);
    var a = 20;
    console.log(a);
}

foo();

The output will be:
undefined
20

Explanation: The variable a inside the function is hoisted but not initialized, so the first console.log(a) prints undefined . After the initialization, the second console.log(a) prints 20 .

Q6: Write a function that removes duplicates from an array.
(Basic)
function removeDuplicates(arr) {
    return [...new Set(arr)];
}

console.log(removeDuplicates([1, 2, 3, 2, 4, 3, 5])); // Output: [1, 2, 3, 4, 5]
Q7: The following code is intended to concatenate two arrays but contains an error. Identify and fix the error.
(Basic)
function concatenateArrays(arr1, arr2) {
    return arr1.concat[arr2];
}

console.log(concatenateArrays([1, 2], [3, 4])); // Expected output: [1, 2, 3, 4]
function concatenateArrays(arr1, arr2) {
    return arr1.concat(arr2);
}

console.log(concatenateArrays([1, 2], [3, 4])); // Output: [1, 2, 3, 4]
Q8: Optimize the following code to find the second largest number in an array.
(Intermediate)
function findSecondLargest(arr) {
    let largest = -Infinity;
    let secondLargest = -Infinity;
    for (let i = 0; i < arr.length; i++) {
        if (arr[i] > largest) {
            secondLargest = largest;
            largest = arr[i];
        } else if (arr[i] > secondLargest && arr[i] < largest) {
            secondLargest = arr[i];
        }
    }
    return secondLargest;
}

console.log(findSecondLargest([1, 2, 3, 4, 5])); // Expected output: 4

The code is already efficient, but it can be slightly refactored for better readability.

function findSecondLargest(arr) {
    let [largest, secondLargest] = [-Infinity, -Infinity];
    for (let num of arr) {
        if (num > largest) {
            [secondLargest, largest] = [largest, num];
        } else if (num > secondLargest && num < largest) {
            secondLargest = num;
        }
    }
    return secondLargest;
}

console.log(findSecondLargest([1, 2, 3, 4, 5])); // Output: 4
Q9: What will be the output of the following code snippet?
(Intermediate)
let x = 10;

function bar() {
    console.log(x);
    if (false) {
        var x = 20;
    }
    console.log(x);
}

bar();

The output will be:
undefined
undefined

Explanation: The variable x inside the function is hoisted but not initialized, so both console.log(x) statements print undefined .

Q9: What will be the output of the following code snippet?
(Intermediate)
let x = 10;

function bar() {
    console.log(x);
    if (false) {
        var x = 20;
    }
    console.log(x);
}

bar();

The output will be:
undefined
undefined

Explanation: The variable x inside the function is hoisted but not initialized, so both console.log(x) statements print undefined .

Q10: Write a function that flattens a nested array.
(Advanced)
function flattenArray(arr) {
    return arr.reduce((flat, toFlatten) => {
        return flat.concat(Array.isArray(toFlatten) ? flattenArray(toFlatten) : toFlatten);
    }, []);
}

console.log(flattenArray([1, [2, [3, [4]], 5]])); // Output: [1, 2, 3, 4, 5]

Request question

Please fill in the form below to submit your question.

Take Your Coding to the Next Level – Explore Workik AI Now!

Join developers who are using Workik’s AI assistance everyday for programming

Sign Up Now

Overview of JAVASCRIPT

What is JavaScript?

What is the history and latest trends in JavaScript development?

What are popular frameworks and libraries in JavaScript?

  • React: A JavaScript library for building user interfaces, maintained by Facebook.
  • Angular: A platform and framework for building single-page client applications using HTML and TypeScript, maintained by Google.
  • Vue.js: An open-source model–view–viewmodel front end JavaScript framework for building user interfaces and single-page applications.
  • Node.js: An open-source, cross-platform, back-end JavaScript runtime environment that runs on the V8 engine and executes JavaScript code outside a web browser.
  • jQuery: A fast, small, and feature-rich JavaScript library that simplifies things like HTML document traversal and manipulation, event handling, and animation.

What are the use cases of JavaScript?

  • Web Development: JavaScript is extensively used for creating interactive web pages and user interfaces.
  • Server-Side Development: With Node.js, JavaScript can be used for server-side scripting, enabling developers to use JavaScript for the entire web development stack.
  • Mobile App Development: Frameworks like React Native allow developers to build mobile applications using JavaScript.
  • Game Development: JavaScript can be used to create games, especially for the web, using frameworks like Phaser.
  • Data Visualization: Libraries like D3.js enable developers to create dynamic and interactive data visualizations.

What are some of the tech roles associated with expertise in JavaScript?

  • Frontend Developer: Specializes in developing the visual and interactive elements of a website or web application.
  • Backend Developer: Uses JavaScript (Node.js) for server-side development.
  • Full-Stack Developer: Proficient in both frontend and backend development, often using JavaScript for both.
  • Mobile Developer: Uses frameworks like React Native to develop mobile applications.
  • JavaScript Engineer: Focuses on creating and maintaining complex JavaScript applications.

What pay package can be expected with experience in JavaScript?

  • Junior JavaScript Developer (0-2 years experience): $80,000 - $100,000 per year.
  • Mid-Level JavaScript Developer (3-5 years experience): $100,000 - $120,000 per year.
  • Senior JavaScript Developer (5+ years experience): $120,000 - $160,000 per year.
  • Frontend Developer: $84,000 - $136,000 per year.
  • Full-Stack Developer: $80,000 - $260,000 per year.