Top 20 JavaScript Interview Questions and Answers for Freshers

Javascript Interview Questions

JavaScript is an essential skill for web development and a must-know for aspiring developers. Whether you’re preparing for your first job or looking to brush up on your JavaScript knowledge, this list of top 20 interview questions and answers will help you get ready for your next interview.

1. What is JavaScript?

Answer: JavaScript is a high-level, interpreted programming language primarily used for creating interactive effects within web browsers. It is an essential part of web development, alongside HTML and CSS.

2. What are the data types supported by JavaScript?

Answer: JavaScript supports several data types, including:

  • Primitive types: undefined, null, boolean, number, string, bigint, symbol
  • Object types: Objects, Arrays, Functions

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

Answer: The == operator checks for equality with type conversion, while === checks for strict equality without type conversion. For example, 5 == '5' is true, but 5 === '5' is false.

4. What is a closure in JavaScript?

Answer: A closure is a function that retains access to its lexical scope, even when the function is executed outside that scope. It allows a function to remember and access variables from an outer function’s scope even after the outer function has finished executing.

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

function innerFunction() {
console.log(outerVariable);
}

return innerFunction;
}

const closure = outerFunction();
closure(); // Output: I am outside!

5. Explain var, let, and const.

Answer:

  • var: Function-scoped or globally-scoped. It can be re-declared and updated.
  • let: Block-scoped. It can be updated but not re-declared within the same scope.
  • const: Block-scoped. It cannot be updated or re-declared. It is used to declare variables whose values are intended to remain constant.

6. What is the purpose of the this keyword?

Answer: The this keyword refers to the object from which the function was called. Its value depends on the context in which it is used (e.g., global context, object method, constructor function).

7. What are arrow functions?

Answer: Arrow functions are a concise syntax for writing functions in JavaScript. They use the => syntax and do not have their own this, arguments, super, or new.target bindings.

const add = (a, b) => a + b;
console.log(add(2, 3)); // Output: 5

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

Answer: An IIFE is a function that is executed immediately after its creation. It is often used to create a new scope and avoid polluting the global namespace.

(function() {
console.log('IIFE executed!');
})();

9. What is event delegation?

Answer: Event delegation is a technique of using a single event listener to manage all events of a particular type for multiple elements. This is achieved by taking advantage of event bubbling.

document.getElementById('parent').addEventListener('click', function(event) {
if (event.target && event.target.matches('button.classname')) {
console.log('Button clicked!');
}
});

10. What are promises in JavaScript?

Answer: Promises are objects representing the eventual completion or failure of an asynchronous operation. They provide a way to handle asynchronous operations more gracefully than callbacks.

let promise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Success!'), 1000);
});

promise.then(result => console.log(result)); // Output after 1 second: Success!

11. What is the use of the async and await keywords?

Answer: async and await are used to handle promises more comfortably. The async keyword is used to declare an asynchronous function, and await is used to pause execution until a promise is resolved.

async function fetchData() {
let response = await fetch('https://api.example.com/data');
let data = await response.json();
console.log(data);
}

12. Explain the concept of hoisting.

Answer: Hoisting is a JavaScript mechanism where variable and function declarations are moved to the top of their containing scope during the compilation phase. This means you can use variables and functions before their declarations in the code.

console.log(hoistedVar); // Output: undefined
var hoistedVar = 'This variable is hoisted!';

hoistedFunction(); // Output: This function is hoisted!
function hoistedFunction() {
console.log('This function is hoisted!');
}

13. What are template literals?

Answer: Template literals are string literals allowing embedded expressions. They are enclosed by backticks (`) and can contain placeholders for variables and expressions using ${}.

let name = 'John';
console.log(`Hello, ${name}!`); // Output: Hello, John!

14. What is destructuring assignment?

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

let [a, b] = [1, 2];
let {name, age} = {name: 'Alice', age: 25};

console.log(a, b); // Output: 1 2
console.log(name, age); // Output: Alice 25

15. What is the difference between null and undefined?

Answer: undefined is a type and value that represents an uninitialized variable or a missing value. null is an object representing the intentional absence of any object value.

let uninitialized;
let empty = null;

console.log(uninitialized); // Output: undefined
console.log(empty); // Output: null

16. What are higher-order functions?

Answer: Higher-order functions are functions that can take other functions as arguments or return functions as their result. They are a powerful feature of JavaScript.

function greet(name) {
return function(message) {
console.log(`Hello, ${name}! ${message}`);
};
}

let greetJohn = greet('John');
greetJohn('Good morning!'); // Output: Hello, John! Good morning!

17. Explain the map, filter, and reduce methods.

Answer:

  • map: Creates a new array populated with the results of calling a provided function on every element in the calling array.
  • filter: Creates a new array with all elements that pass the test implemented by the provided function.
  • reduce: Executes a reducer function on each element of the array, resulting in a single output value.
let numbers = [1, 2, 3, 4, 5];

let doubled = numbers.map(n => n * 2);
let evens = numbers.filter(n => n % 2 === 0);
let sum = numbers.reduce((acc, n) => acc + n, 0);

console.log(doubled); // Output: [2, 4, 6, 8, 10]
console.log(evens); // Output: [2, 4]
console.log(sum); // Output: 15

18. What is the event loop in JavaScript?

Answer: The event loop is a mechanism that allows JavaScript to perform non-blocking I/O operations despite being single-threaded. It manages the execution of asynchronous code by processing the event queue and callback functions.

19. What is the difference between localStorage and sessionStorage?

Answer: Both localStorage and sessionStorage are used for client-side storage. The difference lies in their lifespan:

  • localStorage persists data even after the browser is closed and reopened.
  • sessionStorage persists data only for the duration of the page session (until the browser or tab is closed).

20. What are modules in JavaScript?

Answer: Modules are reusable pieces of code that can be exported from one script and imported into another. They help in organizing code better by encapsulating functionality.

// module.js
export const greet = name => `Hello, ${name}!`;

// main.js
import { greet } from './module.js';
console.log(greet('Alice')); // Output: Hello, Alice!

These questions and answers cover fundamental concepts and techniques in JavaScript. Mastering them will not only prepare you for interviews but also strengthen your overall coding skills. Good luck!

Leave a Reply

Your email address will not be published. Required fields are marked *