DEV Community

Cover image for 25 JavaScript Concept Interview Questions with Examples
Akshaya Mallyar Shet
Akshaya Mallyar Shet

Posted on

25 JavaScript Concept Interview Questions with Examples

JavaScript has become one of the most popular programming languages in the world, powering everything from web applications to server-side development. As a JavaScript developer, understanding key concepts is essential not only for building applications but also for acing interviews. In this blog, we will cover 25 important JavaScript interview questions along with examples to illustrate their application.

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

  • var is function-scoped and can be redeclared.
  • let is block-scoped and cannot be redeclared in the same block.
  • const is also block-scoped but cannot be reassigned.
var a = 1;
let b = 2;
const c = 3;

if (true) {
    var a = 4; // Same variable
    let b = 5; // Scoped to block
    // const c = 6; // Error: variable c is already declared
}
console.log(a); // 4
console.log(b); // 2
// console.log(c); // Error: c is not defined
Enter fullscreen mode Exit fullscreen mode

2. What is hoisting?

Hoisting is the behavior in JavaScript where variable declarations are moved to the top of their scope during compilation. Only the declarations are hoisted, not the initializations.

console.log(x); // undefined
var x = 5;
Enter fullscreen mode Exit fullscreen mode

3. Explain closures.

A closure is a function that remembers its lexical scope even when the function is executed outside that scope. Closures allow for data encapsulation.

function outer() {
    let count = 0;
    return function inner() {
        count++;
        return count;
    };
}
const increment = outer();
console.log(increment()); // 1
console.log(increment()); // 2
Enter fullscreen mode Exit fullscreen mode

4. What are promises?

A Promise is an object that represents the eventual completion (or failure) of an asynchronous operation and its resulting value.

const myPromise = new Promise((resolve, reject) => {
    setTimeout(() => {
        resolve("Done!");
    }, 1000);
});
myPromise.then(result => console.log(result)); // "Done!" after 1 second
Enter fullscreen mode Exit fullscreen mode

5. What is async/await?

Async/await is syntactic sugar built on top of Promises. The async function returns a promise, and await pauses the execution of the function until the promise is resolved.

async function fetchData() {
    const response = await fetch('https://api.example.com/data');
    const data = await response.json();
    return data;
}
Enter fullscreen mode Exit fullscreen mode

6. What are arrow functions?

Arrow functions allow for a more concise syntax when writing function expressions. They also lexically bind the this value.

const add = (x, y) => x + y;
console.log(add(2, 3)); // 5
Enter fullscreen mode Exit fullscreen mode

7. Explain the this keyword.

The value of this indicates the object that is executing the current function. Its value can vary based on how the function is called.

const obj = {
    value: 10,
    getValue: function() {
        return this.value;
    }
};
console.log(obj.getValue()); // 10
Enter fullscreen mode Exit fullscreen mode

8. What is the event loop?

The event loop handles asynchronous calls in JavaScript, allowing non-blocking execution of code. It continuously checks the call stack and the message queue.

console.log("1");
setTimeout(() => console.log("2"), 0);
console.log("3");
// Output: 1, 3, 2
Enter fullscreen mode Exit fullscreen mode

9. What is the difference between == and ===?

== is a loose equality operator that checks for equality after performing type coercion. === is a strict equality operator that checks for equality without type coercion.

console.log(0 == '0');  // true
console.log(0 === '0'); // false
Enter fullscreen mode Exit fullscreen mode

10. What is the purpose of the bind method?

bind creates a new function that, when called, has its this keyword set to the provided value, allowing you to set the context.

const obj = { value: 42 };
const getValue = function() {
    return this.value;
};
const boundGetValue = getValue.bind(obj);
console.log(boundGetValue()); // 42
Enter fullscreen mode Exit fullscreen mode

11. Explain prototypal inheritance.

Prototypal inheritance is a feature in JavaScript that allows objects to inherit properties and methods from other objects. It's achieved via the prototype property.

const animal = {
    eats: true
};
const rabbit = Object.create(animal);
console.log(rabbit.eats); // true
Enter fullscreen mode Exit fullscreen mode

12. What are modules in JavaScript?

Modules are reusable pieces of code that can be exported from one file and imported into another. They help in organizing and encapsulating code.

// module.js
export const pi = 3.14;

// main.js
import { pi } from './module.js';
console.log(pi); // 3.14
Enter fullscreen mode Exit fullscreen mode

13. What is the spread operator?

The spread operator (...) allows an iterable, such as an array, to be expanded in places where zero or more arguments or elements are expected.

const arr1 = [1, 2, 3];
const arr2 = [...arr1, 4, 5];
console.log(arr2); // [1, 2, 3, 4, 5]
Enter fullscreen mode Exit fullscreen mode

14. What is destructuring?

Destructuring is a syntax that allows unpacking values from arrays or properties from objects into distinct variables.

const user = { name: 'Alice', age: 25 };
const { name, age } = user;
console.log(name); // Alice
Enter fullscreen mode Exit fullscreen mode

15. What is a higher-order function?

A higher-order function is a function that takes another function as an argument or returns a function as its result.

function greet(fn) {
    return fn();
}
greet(() => "Hello!"); // "Hello!"
Enter fullscreen mode Exit fullscreen mode

16. What is the difference between synchronous and asynchronous programming?

Synchronous programming executes tasks sequentially, while asynchronous programming allows tasks to be executed concurrently, improving performance.

console.log("Start");
setTimeout(() => console.log("Async"), 0);
console.log("End");
// Output: Start, End, Async
Enter fullscreen mode Exit fullscreen mode

17. What is a callback function?

A callback function is a function passed into another function as an argument, executed after some operation is complete.

function fetchData(callback) {
    setTimeout(() => {
        callback("Data received");
    }, 1000);
}
fetchData(data => console.log(data)); // "Data received" after 1 second
Enter fullscreen mode Exit fullscreen mode

18. What is the instanceof operator?

instanceof is used to check if an object is an instance of a specific constructor or class.

function Person() {}
const person = new Person();
console.log(person instanceof Person); // true
Enter fullscreen mode Exit fullscreen mode

19. What is the purpose of setTimeout and setInterval?

  • setTimeout executes a function after a specified delay.
  • setInterval repeatedly calls a function at specified intervals until cleared.
setTimeout(() => console.log("Executed after 1 second"), 1000);
const intervalId = setInterval(() => console.log("Executed every second"), 1000);
// clearInterval(intervalId); // To stop the interval
Enter fullscreen mode Exit fullscreen mode

20. What are JavaScript data types?

JavaScript has 7 primitive data types: Undefined, Null, Boolean, Number, BigInt, String, and Symbol.

let name = "Alice"; // String
let age = 30;       // Number
let isStudent = false; // Boolean
Enter fullscreen mode Exit fullscreen mode

21. What is a template literal?

Template literals are string literals allowing embedded expressions, using backticks for formatting.

const name = 'Alice';
const greeting = `Hello, ${name}!`;
console.log(greeting); // Hello, Alice!
Enter fullscreen mode Exit fullscreen mode

22. What is a wrapper object?

Wrapper objects allow primitive values to be treated as objects. They enable access to methods associated with the primitive data type.

const string = new String("Hello");
console.log(string.length); // 5
Enter fullscreen mode Exit fullscreen mode

23. Explain the difference between slice and splice.

  • slice returns a shallow copy of a portion of an array.
  • splice changes the contents of an array by removing or replacing existing elements.
const arr = [1, 2, 3, 4, 5];
const sliced = arr.slice(1, 4); // [2, 3, 4]
arr.splice(1, 2); // Removes 2 elements starting from index 1
console.log(arr); // [1, 4, 5]
Enter fullscreen mode Exit fullscreen mode

24. What is the difference between synchronous and asynchronous functions?

  • Synchronous functions block execution until they complete.
  • Asynchronous functions allow other operations to continue during their execution.
function synchronousFunction() {
    console.log("Synchronous Execution");
}

async function asynchronousFunction() {
    console.log("Asynchronous Execution");
    await new Promise(resolve => setTimeout(resolve, 1000));
    console.log("Continuing after 1 second");
}

synchronousFunction();
asynchronousFunction();
Enter fullscreen mode Exit fullscreen mode

25. What is JSON?

JSON (JavaScript Object Notation) is a lightweight data interchange format easy for humans to read and write and machines to parse and generate.

const jsonData = '{"name": "Alice", "age": 25}';
const user = JSON.parse(jsonData);
console.log(user.name); // Alice
Enter fullscreen mode Exit fullscreen mode

Conclusion

Mastering these 25 JavaScript concepts will not only prepare you for technical interviews but also help you become a more proficient developer. Keep practicing, and ensure you understand the underlying principles, as these will serve you well in your coding career!

Top comments (2)

Collapse
 
oculus42 profile image
Samuel Rouse

Lists like these can be helpful to people, as a lot of these do come up in early interview rounds.

I did want to take issue with #22, wrapper objects. The description is technically correct, but the example is misleading. Wrapper objects are temporary and automatic.

// To access String.prototype.length, a temporary object wrapper is created.
'Hello'.length; // 5

// Numbers can include a decimal point, so a second decimal is used in this edge case.
123..toString(); // '123'
Enter fullscreen mode Exit fullscreen mode

The provided example that uses new String() might be demonstrative of the internal process, but I think it will likely cause more confusion than good.

Collapse
 
jonrandy profile image
Jon Randy ๐ŸŽ–๏ธ

A closure is a function that remembers its lexical scope even when the function is executed outside that scope.

This is not correct. A closure is not a function, and ALL functions have the capability you describe.