Javascript Top Interview Questions and Answers for Freshers Part 1

Javascript Top Interview Questions:

Basic Questions

  1. What is JavaScript?
    • Answer: JavaScript is a high-level, dynamic, untyped, and interpreted programming language that is widely used for web development to create interactive and dynamic web pages.
  2. How do you declare a variable in JavaScript?
    • Answer: You can declare a variable using var, let, or const keywords. Example:
      var name = 'John';
      let age = 30;
      const isStudent = true;
  3. What are the differences between var, let, and const?
    • Answer:
      • var has function scope and can be redeclared and updated.
      • let has block scope and can be updated but not redeclared.
      • const has block scope and cannot be updated or redeclared.
  4. What is a function in JavaScript?
    • Answer: A function is a block of code designed to perform a particular task. It is executed when something calls it. Example:
      function greet(name) {
      return 'Hello ' + name;
      }
  5. What is an arrow function?
    • Answer: Arrow functions are a shorthand for writing functions using the => syntax. Example:
      const add = (a, b) => a + b;
  6. What is an object in JavaScript?
    • Answer: An object is a collection of properties, where each property has a key-value pair. Example:
      const person = {
      name: 'John',
      age: 30,
      greet: function() { return 'Hello'; }
      };
  7. How do you create an array in JavaScript?
    • Answer: An array can be created using square brackets []. Example:
      const numbers = [1, 2, 3, 4, 5];
  8. What is a callback function?
    • Answer: A callback function is a function passed into another function as an argument and is executed after some operation has been completed. Example:
      function fetchData(callback) {
      // simulating fetching data
      callback('data');
      }
      fetchData(function(data) {
      console.log(data);
      });
  9. Explain the concept of promises in JavaScript.
    • Answer: Promises are used to handle asynchronous operations. They represent a value that may be available now, or in the future, or never. Example:
      const promise = new Promise((resolve, reject) => {
      if (success) resolve('Success');
      else reject('Error');
      });
  10. What is the use of this keyword?
    • Answer: The this keyword refers to the object it belongs to. It has different values depending on where it is used:
      • In a method, this refers to the owner object.
      • Alone, this refers to the global object.
      • In a function, this refers to the global object.
      • In an event, this refers to the element that received the event.

Intermediate Questions

  1. What is hoisting in JavaScript?
    • Answer: Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their scope before code execution. This means you can use variables and functions before declaring them.
  2. What is the difference between == and ===?
    • Answer: == checks for value equality with type coercion, whereas === checks for both value and type equality without type coercion.
  3. Explain event delegation.
    • Answer: Event delegation is a technique of using a single event listener to manage all similar events by taking advantage of event bubbling. This improves performance and simplifies code. Example:
      document.getElementById('parent').addEventListener('click', function(event) {
      if (event.target.classList.contains('child')) {
      console.log('Child element clicked');
      }
      });
  4. What are closures in JavaScript?
    • Answer: Closures are functions that have access to their own scope, the outer function’s scope, and the global scope. They are created every time a function is created. Example:
      function outer() {
      let count = 0;
      return function inner() {
      count++;
      return count;
      };
      }
      const counter = outer();
      counter(); // 1
      counter(); // 2
  5. What is the fetch API?
    • Answer: The fetch API is used to make asynchronous network requests similar to XMLHttpRequest. It returns a promise that resolves to the response object. Example:
      fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
  6. What is the difference between null and undefined?
    • Answer: null is an assignment value that represents no value, whereas undefined means a variable has been declared but has not yet been assigned a value.
  7. What are template literals in JavaScript?
    • Answer: Template literals are enclosed by backticks (`) and allow embedded expressions. They can contain placeholders using ${expression}. Example:
      const name = 'John';
      const greeting = `Hello, ${name}`;
  8. Explain the concept of the event loop in JavaScript.
    • Answer: The event loop is a mechanism that handles asynchronous callbacks in JavaScript. It allows non-blocking operations by pushing tasks to a queue, and the loop continuously checks the queue to execute tasks when the call stack is empty.
  9. What is a higher-order function?
    • Answer: A higher-order function is a function that takes another function as an argument, or returns a function as a result. Example:
      function higherOrder(fn) {
      return function() {
      return fn() + ' world';
      };
      }
      const sayHello = () => 'Hello';
      const newFunction = higherOrder(sayHello);
      newFunction(); // Hello world
  10. What are default parameters in functions?
    • Answer: Default parameters allow you to initialize named parameters with default values if no value or undefined is passed. Example:
      function greet(name = 'Guest') {
      return `Hello, ${name}`;
      }
      greet(); // Hello, Guest

Advanced Questions

  1. What is destructuring assignment?
    • Answer: Destructuring assignment is a syntax that allows you to unpack values from arrays, or properties from objects, into distinct variables. Example:
      const [a, b] = [1, 2];
      const {name, age} = {name: 'John', age: 30};
  2. What is the difference between map and forEach?
    • Answer: map creates a new array with the results of calling a provided function on every element, while forEach executes a provided function once for each array element but does not return a new array.
  3. What are the different ways to create objects in JavaScript?
    • Answer:
      • Object literals: const obj = { key: 'value' };
      • Constructor functions: function Person(name) { this.name = name; }
      • Object.create: const obj = Object.create(proto);
      • Classes: class Person { constructor(name) { this.name = name; } }
  4. Explain async and await.
    • Answer: async functions return a promise, and await is used to pause execution until the promise is resolved. It makes asynchronous code look and behave like synchronous code. Example:
      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:', error);
      }
      }
      fetchData();
  5. What is a generator function?
    • Answer: A generator function is a function that can be paused and resumed, and it can yield multiple values. It is defined using the function* syntax. Example:
      function* generator() {
      yield 1;
      yield 2;
      yield 3;
      }
      const gen = generator();
      console.log(gen.next().value); // 1
      console.log(gen.next().value); // 2
  6. What is the purpose of the symbol type?
    • Answer: symbol is a primitive data type used to create unique and immutable identifiers, often used for object property keys to avoid name collisions. Example:
      const sym = Symbol('description');
      const obj = { [sym]: 'value' };
  7. Explain the difference between shallow copy and deep copy.
    • Answer: A shallow copy copies an object’s properties without copying nested objects. A deep copy creates a copy of an object and all objects nested within it.
  8. How does Object.assign work?
    • Answer: Object.assign copies all enumerable own properties from one or more source objects to a target object. Example:
      const target = { a: 1 };
      const source = { b: 2 };
      const result = Object.assign(target, source);
      console.log(result); // { a: 1, b: 2 }
  9. What is the purpose of Proxy in JavaScript?
    • Answer: Proxy allows you to create an object with custom behavior for fundamental operations (e.g., property lookup, assignment). Example:
      const handler = {
      get: function(obj, prop) {
      return prop in obj ? obj[prop] : 'default';
      }
      };
      const proxy = new Proxy({}, handler);
      console.log(proxy.nonExistent); // 'default'
  10. What are modules in JavaScript?
    • Answer: Modules are a way to organize and encapsulate code into separate files and namespaces. They allow for better code reuse and maintainability. Example using ES6 modules:
      // module.js
      export const name = 'John';
      export function greet() { return 'Hello'; }
      // main.js
      import { name, greet } from ‘./module’;
      console.log(name); // John
      console.log(greet()); // Hello

Practical Questions

  1. How do you handle errors in JavaScript?
    • Answer: Errors can be handled using try, catch, and finally blocks. Example:
      try {
      throw new Error('An error occurred');
      } catch (error) {
      console.error(error.message);
      } finally {
      console.log('Execution finished');
      }
  2. How do you perform AJAX requests using JavaScript?
    • Answer: AJAX requests can be performed using XMLHttpRequest or the fetch API. Example using fetch:
      fetch('https://api.example.com/data')
      .then(response => response.json())
      .then(data => console.log(data))
      .catch(error => console.error('Error:', error));
  3. How can you manipulate the DOM using JavaScript?
    • Answer: DOM manipulation can be done using methods like getElementById, querySelector, createElement, appendChild, etc. Example:
      const element = document.createElement('div');
      element.textContent = 'Hello, World!';
      document.body.appendChild(element);
  4. Explain the concept of strict mode.
    • Answer: strict mode is a way to opt into a restricted variant of JavaScript, which catches common coding errors and prevents the use of certain features. It is declared at the beginning of a script or a function. Example:
      'use strict';
      x = 3.14; // This will throw an error because x is not declared
  5. What is event bubbling and event capturing?
    • Answer: Event bubbling is the process where an event starts at the target element and bubbles up to the root. Event capturing is the opposite, where the event starts from the root and propagates down to the target. Example:
      document.getElementById('child').addEventListener('click', function(event) {
      console.log('Child clicked');
      }, true); // true for capturing phase
  6. What is the purpose of the bind method?
    • Answer: 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. Example:
      const obj = { x: 42 };
      function getX() {
      return this.x;
      }
      const boundGetX = getX.bind(obj);
      console.log(boundGetX()); // 42
  7. What is the use of apply and call methods?
    • Answer: Both apply and call are used to call a function with a given this value and arguments. call accepts arguments individually, while apply accepts arguments as an array. Example:
      function greet(greeting, punctuation) {
      return greeting + ', ' + this.name + punctuation;
      }
      const obj = { name: 'John' };
      console.log(greet.call(obj, 'Hello', '!')); // Hello, John!
      console.log(greet.apply(obj, ['Hi', '.'])); // Hi, John.
  8. How do you prevent event bubbling?
    • Answer: Event bubbling can be prevented using event.stopPropagation(). Example:
      document.getElementById('child').addEventListener('click', function(event) {
      event.stopPropagation();
      console.log('Child clicked');
      });
  9. What is the difference between synchronous and asynchronous code?
    • Answer: Synchronous code is executed sequentially, blocking further execution until the current task is completed. Asynchronous code allows other tasks to run while waiting for an operation to complete, thus not blocking execution.
  10. How do you make a deep copy of an object?
    • Answer: A deep copy can be made using JSON.parse and JSON.stringify, or by using a custom function to recursively copy properties. Example:
      const obj = { a: 1, b: { c: 2 } };
      const deepCopy = JSON.parse(JSON.stringify(obj));

Coding Challenges

  1. Write a function to reverse a string.
    • Answer:
      function reverseString(str) {
      return str.split('').reverse().join('');
      }
      console.log(reverseString('hello')); // 'olleh'
  2. Write a function to check if a number is prime.
    • Answer:
      function isPrime(num) {
      if (num <= 1) return false;
      for (let i = 2; i < num; i++) {
      if (num % i === 0) return false;
      }
      return true;
      }
      console.log(isPrime(7)); // true
  3. Write a function to find the maximum value in an array.
    • Answer:
      function findMax(arr) {
      return Math.max(...arr);
      }
      console.log(findMax([1, 2, 3, 4, 5])); // 5
  4. Write a function to remove duplicates from an array.
    • Answer:
      function removeDuplicates(arr) {
      return [...new Set(arr)];
      }
      console.log(removeDuplicates([1, 2, 2, 3, 4, 4])); // [1, 2, 3, 4]
  5. Write a function to merge two sorted arrays into one sorted array.
    • Answer:
      function mergeSortedArrays(arr1, arr2) {
      let merged = [];
      let i = 0, j = 0;
      while (i < arr1.length && j < arr2.length) {
      if (arr1[i] < arr2[j]) {
      merged.push(arr1[i]);
      i++;
      } else {
      merged.push(arr2[j]);
      j++;
      }
      }
      return merged.concat(arr1.slice(i)).concat(arr2.slice(j));
      }
      console.log(mergeSortedArrays([1, 3, 5], [2, 4, 6])); // [1, 2, 3, 4, 5, 6]
  6. Write a function to flatten a nested array.
    • Answer:
      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]])); // [1, 2, 3, 4, 5]
  7. Write a function to find the factorial of a number.
    • Answer:
      function factorial(n) {
      if (n === 0) return 1;
      return n * factorial(n - 1);
      }
      console.log(factorial(5)); // 120
  8. Write a function to check if a string is a palindrome.
    • Answer:
      function isPalindrome(str) {
      const reversed = str.split('').reverse().join('');
      return str === reversed;
      }
      console.log(isPalindrome('racecar')); // true
  9. Write a function to find the intersection of two arrays.
    • Answer:
      function arrayIntersection(arr1, arr2) {
      return arr1.filter(value => arr2.includes(value));
      }
      console.log(arrayIntersection([1, 2, 3], [2, 3, 4])); // [2, 3]
  10. Write a function to implement binary search.
    • Answer:
      function binarySearch(arr, target) {
      let left = 0;
      let right = arr.length - 1;
      while (left <= right) {
      const mid = Math.floor((left + right) / 2);
      if (arr[mid] === target) return mid;
      if (arr[mid] < target) left = mid + 1;
      else right = mid - 1;
      }
      return -1;
      }
      console.log(binarySearch([1, 2, 3, 4, 5], 3)); // 2