JavaScript Interview Questions and Answers for 2023 (Part 1)

In this article we will provide you with a comprehensive list of common JavaScript interview questions and answers that often come up in interviews

  1. What is JavaScript, and what are its key features?

Javascript is a popular high-level programming language used primarily for creating dynamic web pages and interactive frontend UI.

Javascript is a lightweight and interpreted language meaning it does need to be compiled before running and can be executed directly by a web browser.

Some key features of JavaScript include:

  • Interactivity:- JavaScript enables interactive user experience including animations, form validation, and dynamic content updates without the need to reload the page.

  • flexibility:- Javascript is a flexible language that can be used for both frontend and backend development.

  • Cross-Platform Compatibility:- JavaScript can be used on a wide range of platforms, including desktops, mobile devices, and web browsers.

  • Object-oriented:- This means that it uses objects and classes to organize and structure code, making it more efficient and easier to read.

  1. What’s the difference between JavaScript and Java?

JavaScript

Java

It is an interpreted language, meaning that it is executed directly by a web browser or server.

It is a compiled language, meaning that it is compiled into machine code that can run directly on a computer's processor.

JavaScript is an object-based language that supports object-oriented programming but mostly used functional based language

Java is a strongly object-oriented language

JavaScript is a dynamically typed language which means that variables do not have a predefined type.

Java is a strongly typed language which means that variables have a predefined type.

JavaScript is designed to run in web browsers or with Node.js on servers.

Java is designed to be platform-independent and can run on any system with a JVM installed

Java is commonly used for developing large-scale enterprise-level applications

JavaScript is commonly used for developing front-end web applications and client-side scripts.

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

In JavaScript, var, let, and const are used to declare variables, but they have some differences in terms of scope, reassignment, and hoisting.

  1. Scope:

    • var: Variables declared with var are function-scoped. They are accessible within the function they are defined in or, if defined outside any function, they become globally scoped.

    • let and const: Variables declared with let and const are block-scoped. They are accessible only within the block they are defined in, such as within a loop or an if statement.

  2. Reassignment:

    • var and let: Variables declared with var and let can be reassigned to new values.

    • const: Variables declared with const are read-only and cannot be reassigned once a value is assigned. However, for objects and arrays assigned to const, their properties or elements can still be modified.

  3. Hoisting:

    • var: Variables declared with var are hoisted to the top of their scope. This means you can access and use a variable before it is declared, although its value will be undefined until the assignment is encountered.

    • let and const: Variables declared with let and const are hoisted to the top of their block scope, but they are not initialized. They are not accessible before the declaration, which helps prevent the use of variables before they are defined.

  4. Block Scope:

    • var: Variables declared with var are not block-scoped, so they can be accessed outside of the block they are declared in.

    • let and const: Variables declared with let and const are block-scoped, meaning they are limited to the block in which they are defined. They are not accessible outside that block.

Here are some examples to illustrate the differences:

// Example 1: var
function example1() {
  var x = 10;
  if (true) {
    var x = 20;
    console.log(x); // Output: 20
  }
  console.log(x); // Output: 20
}

// Example 2: let
function example2() {
  let y = 10;
  if (true) {
    let y = 20;
    console.log(y); // Output: 20
  }
  console.log(y); // Output: 10
}

// Example 3: const
function example3() {
  const z = 10;
  if (true) {
    const z = 20;
    console.log(z); // Output: 20
  }
  console.log(z); // Output: 10
}

// Example 4: const with object
function example4() {
  const person = {
    name: 'John',
    age: 30
  };

  person.age = 35; // Allowed
  console.log(person); // Output: { name: 'John', age: 35 }

  person = {} // Not allowed, will throw an error
}

In Example 1, the var variable x is function-scoped and can be accessed both inside and outside the if block.

In Example 2, the let variable y is block-scoped, so it has different values inside and outside the if block.

In Example 3, the const variable z is also block-scoped, but it cannot be reassigned after the initial assignment.

In Example 4, const is used to declare an object

  1. What is the difference between "==" and "===" in JavaScript?

\== (called loose equality) is used to compare two variables regardless of the variable's data type.

\=== (called strict equality) is used to compare two variables, but this will check strict type, which means it will check the data type and compare two values.

Example:

console.log(10 == "10"); // Output: true (loose equality, performs type coercion)
console.log(10 === "10"); // Output: false (strict equality, types are different)

console.log(null == undefined); // Output: true (loose equality, special case of type coercion)
console.log(null === undefined); // Output: false (strict equality, types are different)

console.log(true == 1); // Output: true (loose equality, performs type coercion)
console.log(true === 1); // Output: false (strict equality, types are different)

console.log(0 == false); // Output: true (loose equality, performs type coercion)
console.log(0 === false); // Output: false (strict equality, types are different)
  1. What is an object in JavaScript?

In JavaScript, objects are a fundamental data type used to store and organize data. They are key-value pairs, where the keys are strings (or symbols) that uniquely identify the values. Objects can hold any type of value, including primitive data types (such as numbers and strings) and other objects.

Objects in JavaScript are dynamic, meaning that their properties can be added, modified, or deleted at runtime.

For Example

const employee = {
  id: 7,
  name: 'John',
  dept: 'HR'
}

Here is an employee object with three properties: id, name, and dept as keys and 7, 'John', and 'HR' as values.

  1. How do you create an object in JavaScript?

Creating a JavaScript Object

Using an Object Literal

This is the easiest way to create a JavaScript Object.

const person = {
  name: 'John',
  age: 30,
  city: 'New York'
};

In this approach, an object is defined using curly braces {} and the properties and their values are specified within the braces using key-value pairs.

Object Constructor

const person = new Object();
person.name = 'John';
person.age = 30;
person.city = 'New York';

In this approach, an object is created using the Object constructor, and properties are added using dot notation or bracket notation.

Factory Function

A factory function is a function that returns an object. It allows you to create multiple objects with the same structure and behavior.

function createPerson(name, age, city) {
  return {
    name: name,
    age: age,
    city: city,
    sayHello: function() {
      console.log('Hello, my name is ' + this.name);
    }
  };
}

const person = createPerson('John', 30, 'New York');

Object.create()

The Object.create() method creates a new object and sets the prototype of that object to the specified object.

const person = Object.create({
  name: 'John',
  age: 30,
  city: 'New York'
});

ES6 Classes

ES6 introduced the class syntax, which provides a more concise and structured way to define objects and their behavior.

class Person {
  constructor(name, age, city) {
    this.name = name;
    this.age = age;
    this.city = city;
  }

  sayHello() {
    console.log('Hello, my name is ' + this.name);
  }
}

const person = new Person('John', 30, 'New York');
  1. What is an array in JavaScript?

An array is a special variable, which can hold more than one value.

or

an array is a data structure used to store multiple values in a single variable. It is an ordered collection of elements, where each element can be accessed by its index or position within the array.

They are defined using square brackets "[]" and elements are separated by commas ",".

Example:

const numbers = [1, 2, 3, 4];

In this example, we define an array called "numbers" that contains four elements, which are all numbers.

  1. How do you create an array in JavaScript?

Different ways to create Arrays

Using Assignment operator: It is most common way to create an array in JavaScript would be to assign that array to a variable like this

const cars = ["Saab", "Volvo", "BMW"];
console.log(cars); // ["Saab", "Volvo", "BMW"]

Using Array constructor: Another way to create an array is to use the new keyword with the Array constructor. the output will same

const cars = new Array("Saab", "Volvo", "BMW");
console.log(cars); // ["Saab", "Volvo", "BMW"]

Using Array.of(): Another way to create an array is to use the Array.of() method. This method takes in any number of arguments and creates a new array instance.

const cars = Array.of("Saab", "Volvo", "BMW");
console.log(cars); // ["Saab", "Volvo", "BMW"]

Using split() method: The split() method splits a string into an array of substrings

const cars = "Saab Volvo BMW";
console.log(cars.split(" ");  // [ 'saab', 'volvo', 'bmw' ]
  1. What are the various data types that exist in JavaScript?

These are the different types of data that JavaScript supports:

  • Boolean - Booleans can only have two values: true or false. here true means "yes" or 1. false means "No" or 0.

      let x = 5; 
      let y = 5; 
      let z = 6; 
      alert(x > y) // Returns false alert(x < z) //Returns true
      alert(x===y) //Returns true
    
  • Null - Null represents “nothing”, “empty” or “value unknown”.

      let x=null; // null 
      let y=console.log(typeof x); // object
    
  • Undefined - In javascript, when a variable is declared, but not assigned, then its value is undefined.

      let age; alert(age); // displays "undefined"
    

    it is possible to explicitly assign undefined to a variable:

      let age = 100; // change the value to undefined 
      age = undefined; 
      alert(age); // "undefined"
    
  • Number - a number used to store numeric values both integers and floating-point numbers

      let x=12; // without decimals let y=12.45; // with decimals
    
  • String - A string is a series of characters like "My name is Tarun".
    Strings are written with quotes. You can use single or double quotes

      let x="my name is" ; // here x is my name is 
      let y='my name is' ; // here y is my name is
    
  • Object - objects are written with curly braces {} .It is used to store the collection of data in key: value pairs separated by commas.

      const person = {
      name: 'John', 
      age: 30, 
      address: { 
      street: '123 Main St', 
      city: 'Anytown', 
      state: 'CA' },
      };
    
  • Symbols - It represents a unique identifier. Symbols are immutable and unique, meaning that once a symbol is created, its value cannot be changed, and no two symbols can have the same value.

      var s1 = Symbol(); 
      var s2 = Symbol(); 
      console.log(s1 === s2); // false
    
  • Bigint - JavaScript BigInt variables are used to store big integer values that are too big to be represented by a normal JavaScript Number.

      let x = 123456789012345678901234567890n; //123456789012345678901234567890n 
      let y = BigInt(123456789012345678901234567890) //123456789012345678901234567890n
    
  1. What is a closure in JavaScript?

Closures are an important concept in JavaScript that allow functions to access variables from an outer (enclosing) scope even after the outer function has finished executing. In simpler terms, a closure gives you access to an outer function's scope from an inner function.

Here's an example to illustrate closures:

function outer() {
  const outerVar = 'I am from outer';

  function inner() {
    console.log(outerVar);
  }

  return inner;
}

const closureFunc = outer();
console.log("output:", closureFunc) 
//output: ƒ inner() {
// console.log(outerVar);
// }    
closureFunc(); // Output: I am from outer

In the above example, the outer() function defines an inner function inner(). The inner() function has access to the outerVar variable declared in its outer scope, even after the outer() function has finished executing. When we invoke closureFunc(), it still has access to the outerVar variable and prints its value. the outer function returns the inner function. (function returns a function)