JavaScript Interview Questions & Answers

JavaScript is one of the most popular programming languages in use today, and it’s widely used in web development, server-side programming, and even desktop and mobile applications. Besides, there are several reasons to learn JavaScript.

But once you become a JavaScript developer and looking to try your hand at any of the several JavaScript jobs, it’s important to have a solid understanding of the language’s features, syntax, and quirks.

To help you prepare for your next JavaScript interview, we’ve compiled a list of the most common JavaScript interview questions with answers. From basic language features to more advanced concepts like closures and event handling, these questions cover a range of topics that any JavaScript developer should be familiar with.

Explore the best FREE JavaScript courses to start learning and creating your own projects & earn a free certification after completion.

Table of Contents hide

What is JavaScript?

JavaScript is a high-level programming language that is used primarily to create interactive web pages and applications. It is an object-oriented language that runs on the client side, meaning that it is executed by the user’s web browser.

What is the Difference Between JavaScript and Java?

JavaScript and Java are two different programming languages with different syntaxes and purposes.

Java is a general-purpose, object-oriented programming language used for creating complex compiled programs that run on implementations of the Java Virtual Machine (JVM) on almost every platform.

Example of a basic Java “Hello, World!” program:

// Your First Program

class HelloWorld {
    public static void main(String[] args) {
        System.out.println("Hello, World!"); 
    }
}

JavaScript is a lightweight scripting language used mainly for adding interactivity and dynamic behavior to web pages. Today, the popularity of JavaScript also growing as a server-side technology since the release of Node.js.

Example of a basic JavaScript “Hello, World!” program:

// the hello world program
console.log('Hello World');

What Are the JavaScript Data Types

JavaScript has eight basic built-in data types and they are:

  • Number – used to represent numeric values, including integers and floating-point numbers [example: 11, -5.5, 3.14159]
  • String – used to represent textual data [examples: “hello”, ‘world’, “123”].
  • Boolean – used to represent logical values, either true or false [examples: true, false].
  • BigInt – used to represent integers with arbitrary precision [example: 999999999999999].
  • Null – used to represent the intentional absence of any object value [example: null].
  • Undefined – used to represent a declared variable that has not been assigned a value [example: let myVar;].
  • Symbol – a unique value that can be used as an identifier for object properties [example: const mySymbol = Symbol();].
  • Object – a complex data type that can hold key-value pairs, functions, and other data types [example: const myObj = {name: “Jane”, age: 31, hobbies: [“reading”, “swimming”]}].

It’s important to note that, unlike other programming languages, JavaScript is a dynamically typed language, meaning that the data type of a variable can change during runtime.

For example, a variable can be assigned a value of type Number and later be reassigned to a value of type String.

Difference Between Null and Undefined in JavaScript

In JavaScript, null and undefined both represent the absence of a value, but they are used differently. Null is an explicitly assigned value that indicates no value or no object, whereas undefined means a variable has been declared but has not been assigned a value.

undefined is a primitive value that is automatically assigned to a variable that has been declared but has not been assigned a value. It can also be explicitly assigned to a variable.

null is also a primitive value that is used to represent the intentional absence of any object value. It can be assigned to a variable explicitly, but it will never be automatically posted by JavaScript.

Example of Null and Undefined program:

let myVar1;
console.log(myVar1); // Output: undefined

let myVar2 = null;
console.log(myVar2); // Output: null

In the code above, myVar1 is declared but not assigned a value, so its value is automatically set to undefined. On the other hand, myVar2 is explicitly assigned the value null.

It’s also worth noting that null is considered to be a primitive data type in JavaScript, while undefined is not considered to be a data type at all, but rather a value that represents the absence of a value.

What Is the Typeof Operator in JavaScript

The typeof operator as used in JavaScript helps to determine the data type of a value or variable. It returns a string indicating the type of the operand.

let myVar = "hello";
console.log(typeof myVar); // Output: "string"

In the above example, typeof is used to determine the data type of the myVar variable, which is a string.

What Are the Types of Operators in JavaScript

JavaScript has several types of operators, including:

  • arithmetic operators – used to perform arithmetic calculations [example: +, -, *, /, %].
  • assignment operators – used to assign values to variables [example: =, +=, -=, *=, /=, %=].
  • comparison operators – used to compare two values [example: ==, ===, !=, !==, <, >, <=, >=].
  • logical operators – used to perform logical operations [example: &&, ||, !].
  • bitwise operators – used to perform operations on binary representations of numbers [example: &, |, ^, ~, <<, >>, >>>].
  • unary operators – used to perform various unary operations [example: ++, --, typeof].
  • ternary operator – used to replace an if..else statement [example: ?:].

What Is the isNaN() Function in JavaScript

The isNaN() function in JavaScript helps to determine whether a value is NaN (Not a Number). It returns true if the value is NaN, and false otherwise.

Here’s an example:

console.log(isNaN(5)); // Output: false
console.log(isNaN("hello")); // Output: true

In this example, the isNaN() function is used to determine whether the value 5 and the string “hello” are NaN.

Difference Between == and === Operators in JavaScript

The == and === operators are used to compare values in JavaScript, but they work in slightly different ways.

The == operator in JavaScript is used for loose equality comparison, meaning that it compares the values of two operands without checking their data types.

On the other hand, the === operator is used for strict equality comparison, meaning that it compares the values of two operands as well as their data types.

The == operator compares values for equality after performing type coercion, which means that it will attempt to convert the operands to the same data type before comparing them.

Here’s an example:

console.log(5 == "10"); // Output: true

In this example, the == operator converts the string “10” to the number 10 before comparing the two values.

console.log(5 === "10"); // Output: false

In this example, the === operator does not convert the string “10” to a number, so the two values are not considered equal.

Difference Between Let, Var, and Const in JavaScript

In JavaScript, the let, var, and const help in declaring variables.

The main differences between them are:

  • var was the original way to declare variables in JavaScript, and it has function-level scoping, which means that variables declared with var are accessible throughout the entire function in which they are declared, regardless of block scope.
  • let and const were introduced in ES6 and have block-level scoping, which means that variables declared with let or const are only accessible within the block in which they are declared, such as inside a loop or conditional statement.
  • const is used to declare constants, which cannot be reassigned once they are initialized.

Here’s an example:

const PI = 3.14159;
console.log(PI); // Output: 3.14159

PI = 3.14; // Error: Assignment to constant variable

What Is Scope in JavaScript

Scope in JavaScript refers to the accessibility of variables and functions in different parts of a program. ‘

There are two types of scope in JavaScript: global scope and local scope.

  • Global scope refers to variables that are declared outside of any function, and they are accessible throughout the entire program.
  • Local scope refers to variables that are declared inside a function or block, and they are only accessible within that function or block.

Here’s an example:

let globalVar = "I'm global";

function myFunction() {
  let localVar = "I'm local";
  console.log(localVar); // Output: "I'm local"
  console.log(globalVar); // Output: "I'm global"
}

console.log(globalVar); // Output: "I'm global"
console.log(localVar); // Error: localVar is not defined

In the example, globalVar is declared outside of the function, so it has a global scope and is accessible throughout the program. localVar is declared inside the function, so it has local scope and is only accessible within the function.

What Is Hoisting in JavaScript

Hoisting in JavaScript is a behavior where both variable and function declarations are moved to the top of their respective scopes during the compilation phase, regardless of where they are declared in the code.

This means that they can be accessed before they are declared in the code. However, only variable declarations are hoisted, not their initialization.

Here’s an example:

console.log(myVar); // Output: undefined
var myVar = "hello";

In this example, the myVar variable is declared after it is used in the console.log() statement. However, because of hoisting, the variable declaration is moved to the top of the scope, so the code is equivalent to:

var myVar;
console.log(myVar);
myVar = "hello";

What Is Closure in JavaScript

Closure in JavaScript is a feature that allows a function to access variables from its outer function or lexical scope even after the outer function has returned.

Closures are commonly used to create private variables and functions.

function outerFunction() {
  let privateVariable = "I am private";

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

  return innerFunction;
}

let closure = outerFunction();
closure(); // Output: "I am private"

What is ‘This’ Keyword in JavaScript

The ‘this‘ keyword in JavaScript is used to refer to the current object. Its value depends on how the function is called. In a global context, this refers to the global object (i.e., a window in a web browser).

In an object method, this refers to the object that the method belongs to.

;
let myObject = {
  myMethod: function() {
    console.log(this); // Output: { myMethod: [Function: myMethod] }
  }
};

myObject.myMethod();

The ‘this‘ keyword in this example is used within an object method, so it refers to the myObject object.

Difference Between ‘Let’ and ‘Var’ in Javascript

The difference between let and var exists in their scope and hoisting characteristics:

  • Scopevar has function scope, while let has block scope, which means that variables declared with var are available throughout the entire function, while variables declared with let are only available within the block in which they are declared.
  • Hoistingvar declarations are hoisted to the top of their scope, while let declarations are not, which means that you can use a var variable before it is declared, but not a let variable.

Here’s an example:

function example() {
  var a = 1;
  if (true) {
    var b = 2;
    let c = 3;
  }
  console.log(a); // 1
  console.log(b); // 2
  console.log(c); // ReferenceError: c is not defined
}

Difference Between ‘Const’ and ‘Let’ in Javascript

The difference between the two exists in terms of:

  • Assignmentconst variables cannot be reassigned to a new value once they are declared, while let variables can.
  • Initializationconst variables must be initialized when they are declared, while let variables can be initialized later.

Here’s an example:

const PI = 3.14159;
PI = 3.14; // TypeError: Assignment to constant variable.
let x;
x = 1;

Different Ways to Declare Functions in JavaScript

There are three ways to declare a function in JavaScript: function declarations, function expressions, and arrow functions.

Function declarations use the function keyword followed by a function name and a block of code. They are hoisted to the top of their scope, so they can be called before they are declared.

function myFunction() {
  console.log("Hello, world!");
}

myFunction();

Function expressions define a function as a value within an expression, and they can be named or anonymous. They are not hoisted, so they must be defined before they are called.

let myFunction = function() {
  console.log("Hello, world!");
};

myFunction();

Arrow functions are a more concise way to define functions, and they have simpler syntax. They are not hoisted, and they do not have their own value.

let myFunction = () => {
  console.log("Hello, world!");
};

myFunction();

Difference Between call() and apply() Methods in JavaScript

Both the call() and apply() methods are used to invoke a function with a specific value and arguments. However, they differ in how they accept arguments.

The main difference between call() and apply() methods in JavaScript is how arguments are passed to the function. With call(), arguments are passed in individually, whereas with apply(), arguments are passed in as an array.

The call() method takes this value as the first argument, followed by the function arguments as individual arguments:

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

greet.call(null, 'Wilson');

The apply() method takes this value as the first argument, followed by the function arguments as an array:

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

greet.apply(null, ['John']);

In most cases, you can use either method interchangeably. The apply() method is useful when you have an array of arguments that you want to pass to a function, while the call() method is useful when you have a list of arguments.

Different Types of Loops in JavaScript

There are four types of loops in JavaScript:

  • for loop
  • while loop
  • do-while loop
  • for-in loop (used to iterate over object properties).

What Is Break Statement in JavaScript

The break statement in JavaScript is used to terminate a loop, a switch statement, or a labeled statement. When used in a loop, the break statement causes the loop to immediately terminate, and execution continues with the next statement following the loop. This is useful when you want to exit a loop prematurely, based on a certain condition.

For example:

for (let i = 0; i < 10; i++) {
  if (i === 5) {
    break;
  }
  console.log(i);
}

In this code, the loop will iterate from 0 to 4, and then the break statement will be encountered when i is equal to 5. This will cause the loop to immediately terminate, and the code execution will continue with the next statement after the loop.

You can also use it in a switch statement to terminate the current case and exit the switch statement. This is useful when you want to prevent a fall-through to the next case.

For example:

let fruit = "orange";
switch (fruit) {
  case "apple":
    console.log("This is an apple.");
    break;
  case "orange":
    console.log("This is an orange.");
    break;
  case "banana":
    console.log("This is a banana.");
    break;
  default:
    console.log("I don't know what this is.");
}

In this code, the break statement is used to exit each case after the appropriate message is logged. Without the break statements, the code would “fall-through” to the next case, and all subsequent cases would be executed as well.

What is Memoization in JavaScript

Memoization is a technique in JavaScript used to optimize function performance by caching the results of expensive function calls and returning the cached result when the same inputs occur again.

The concept is to store the result of a function call in memory so that we don’t have to execute the function again with the same input.

Here’s an example of how you can use memorization:

function memoize(func) {
  const cache = {};
  return function(...args) {
    const key = JSON.stringify(args);
    if (cache[key]) {
      return cache[key];
    }
    const result = func.apply(this, args);
    cache[key] = result;
    return result;
  };
}

function add(a, b) {
  console.log('Calculating sum of', a, 'and', b);
  return a + b;
}

const memoizedAdd = memoize(add);

console.log(memoizedAdd(1, 2)); //Calculating sum of 1 and 2 //3
console.log(memoizedAdd(1, 2)); //3 (no calculation performed)
console.log(memoizedAdd(2, 3)); //Calculating sum of 2 and 3 //5
console.log(memoizedAdd(2, 3)); //5 (no calculation performed)

In this example, we define a memoize function that takes in a func as an argument and returns a new function. The returned function checks if the result of the func has already been calculated by checking if the inputs are already in the cache.

If the inputs are already in the cache, it returns the cached result; otherwise, it calculates the result by executing the func and caching the result.

What Is a Generator Function in JavaScript

A generator function is a special type of function in JavaScript that can pause its execution using the yield keyword and can be resumed later.

Generator functions are useful for generating sequences of values lazily, and for creating asynchronous control flow.

Here’s an example of a generator function:

function* fibonacci() {
  let a = 0, b = 1;
  while (true) {
    yield a;
    [a, b] = [b, a + b];
  }
}

const fib = fibonacci();

for (let i = 0; i < 10; i++) {
  console.log(fib.next

What Is a try-catch Statement in JavaScript

The try-catch statement is used to handle exceptions that might occur in your JavaScript code. The try block contains the code that might throw an exception, and the catch block handles the exception if it occurs.

Code example is as shown below;

try {
  // Code that might throw an exception
  const result = 10 / 0; // Divide by zero
} catch (error) {
  // Handle the exception
  console.log('An error occurred:', error);
}

Our aim in the above example is to try to divide 10 by 0, which is not a valid operation and will throw an exception. We catch the exception in the catch block and log an error message to the console.

How Do You Implement Inheritance in JavaScript

JavaScript uses prototype-based inheritance. We can create a parent object and set its properties and methods. Then we can create child objects and inherit those properties and methods by setting the child’s prototype to the parent object.

Example code:

function Animal(name) {
  this.name = name;
}

Animal.prototype.sayName = function() {
  console.log(this.name);
};

function Dog(name, breed) {
  Animal.call(this, name);
  this.breed = breed;
}

Dog.prototype = Object.create(Animal.prototype);
Dog.prototype.constructor = Dog;

Dog.prototype.bark = function() {
  console.log("Woof!");
};

let dog = new Dog("Max", "German Shepherd");
dog.sayName(); // Output: "Max"
dog.bark(); // Output: "Woof!"

What Is Finally Statement in JavaScript

The finally statement in JavaScript is used in conjunction with try and catch statements to define a block of code that should be executed regardless of whether an exception is thrown or not.

The syntax for using the finally statement is as follows:

try {
  // code that may throw an exception
} catch (error) {
  // code to handle the exception
} finally {
  // code to be executed regardless of whether an exception is thrown or not
}

The finally block is executed after the try and catch blocks, and it will always be executed, even if an exception is thrown or the control flow is redirected elsewhere in the code.

This makes it useful for tasks that should be performed regardless of the outcome of the try and catch blocks, such as releasing resources, closing files, or resetting variables.

For example, consider the following code snippet:

let result;
try {
  result = performOperation();
} catch (error) {
  console.error("An error occurred:", error);
  result = null;
} finally {
  cleanup();
}

In this code, the performOperation() function may throw an exception, and the catch block is used to handle the exception and set the result variable to null. However, regardless of whether an exception is thrown or not, the finally block will be executed to perform any necessary cleanup tasks.

Overall, the finally statement in JavaScript is a powerful feature that allows developers to ensure that critical cleanup code is executed even if an unexpected error occurs.

What Is Event bubbling in JavaScript

Event bubbling is a behavior in JavaScript where an event that is triggered on an element will also trigger on its parent elements in the DOM tree, propagating up the hierarchy until it reaches the root element.

This means that if you have a click event on a child element, it will also trigger the click event on all of its parent elements.

Here is an example code to demonstrate event bubbling:

const parent = document.getElementById('parent');
const child = document.getElementById('child');
const btn = document.getElementById('btn');

parent.addEventListener('click', function(event) {
  console.log('Parent clicked');
});

child.addEventListener('click', function(event) {
  console.log('Child clicked');
});

btn.addEventListener('click', function(event) {
  console.log('Button clicked');
});

When you click the “Click me” button, you will see three messages in the console: “Button clicked“, “Child clicked“, and “Parent clicked“.

This is because the click event is triggered on the button first, then bubbles up to the child element, and finally to the parent element.

What Is forEach() Method in JavaScript

The forEach method is used to execute a provided function once for each array element. It is often used to perform side effects on each element of an array.

The code sample is as follows:

const array = [1, 2, 3];
array.forEach((element) => {
  console.log(element);
});

The above example defines an array and call the forEach method on it. The provided function logs each element of the array to the console.

What Is map() Method in JavaScript

The map method in JavaScript is used to loop through an array and create a new array with the results of calling a function on each element in the array.

It is often used to transform the elements of an array.

const array = [1, 2, 3];
const newArray = array.map((element) => {
  return element * 2;
});
console.log(newArray); // [2, 4, 6]

In this example, we define an array and call the map method on it. The provided function multiplies each element of the array by 2, and the resulting array is stored in a new variable.

What Is Event Delegation in JavaScript

Event delegation is a technique in JavaScript where instead of attaching an event listener to every individual element, you attach it to a common ancestor element and use the event.target property to determine which specific element triggered the event.

Here’s an example of an event delegation:

const list = document.getElementById('list');

list.addEventListener('click', (event) => {
  if (event.target.tagName === 'LI') {
    event.target.classList.toggle('completed');
  }
});

In this example, we attach a click event listener to the ul element with the ID of list. When an element inside the ul is clicked, the event bubbles up to the ul element, and we use the event.target property to check if the clicked element is an li element. If it is, we toggle its completed class.

What Is every() Method in JavaScript

The every() method in JavaScript is used to loop through an array and return true if all elements pass a certain condition specified in a callback function.

It returns a Boolean value indicating whether all elements pass the test.

const array = [2, 4, 6];
const allEven = array.every((element) => {
  return element % 2 === 0;
});
console.log(allEven); // true

In the above example, we define an array and call the every method on it. The provided function tests whether each element of the array is even. Since all elements are even, the every method returns true.

What Is Promise Object in JavaScript

A promise is an object that represents the eventual completion or failure of an asynchronous operation and allows you to handle the result of that operation asynchronously.

Promises have three states: pending, fulfilled, or rejected.

Example of Promise object code:

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

promise.then((result) => {
  console.log(result); // 'Success!'
}).catch((error) => {
  console.error(error);
});

In this example, we create a new promise that resolves after 1 second with the value ‘Success!‘. We then use the then() method to handle the result of the promise, and the catch() method to handle any errors that occur.

What Is sort() Method in JavaScript

The sort method in JavaScript is used to sort the elements of an array in place (i.e., it modifies the original array) according to a specified sorting order.

Example of sort() method code:

const array = [3, 1, 2];
array.sort();
console.log(array); // [1, 2, 3]

In this example, we define an array and call the sort method on it. The resulting array is sorted in ascending order.

What Is Date Object in JavaScript

The Date object in JavaScript is used to work with dates and times, which allows you to create and manipulate dates, set and retrieve specific date and time values, and perform various operations on dates.

Here’s an example of creating a new Date object and displaying the current date and time:

const now = new Date();
console.log(now);

Output:

2023-03-15T17:20:34.082Z

What Is setInterval() Method in JavaScript

The setInterval method is used to repeatedly execute a function at a set interval. It takes two arguments: the function to be executed, and the time interval in milliseconds.

Here’s an example of using setInterval to display the current time every second:

function displayTime() {
  const now = new Date();
  console.log(now.toLocaleTimeString());
}

setInterval(displayTime, 1000);

Output (updated every second):

5:20:34 PM
5:20:35 PM
5:20:36 PM
...

What Is setTimeout Method in JavaScript

The setTimeout method is used to execute a function after a set time delay. It takes two arguments: the function to be executed, and the time delay in milliseconds.

Here’s an example of using setTimeout to display a message after a 5-second delay:

function showMessage() {
  console.log("Hello, world!");
}

setTimeout(showMessage, 5000);

Output (after a 5-second delay):

Hello, world!

What Is clearTimeout Method in JavaScript

The clearTimeout method is used to cancel a timeout created with the setTimeout method before it executes. It takes one argument: the ID of the timeout to be canceled.

Here’s an example of using clearTimeout to cancel a timeout:

function showMessage() {
  console.log("Hello, world!");
}

const timeoutId = setTimeout(showMessage, 5000);

clearTimeout(timeoutId); // cancel the timeout

In this example, the timeout is canceled before it has a chance to execute, so “Hello, world!” will not be displayed in the console.

What Is toString() Method in JavaScript

The toString method is used to convert a JavaScript object to a string. This method can be called on any object, and it returns a string representation of that object.

Here’s an example of using the toString method on a number:

const num = 42;
const str = num.toString();
console.log(str);

Output:

"42"

What Is valueOf() Method in JavaScript

The valueOf method is used to return the primitive value of a JavaScript object. This method can be called on any object, and it returns the primitive value of that object.

Here’s an example of using the valueOf method on a date object:

const now = new Date();
const timestamp = now.valueOf();
console.log(timestamp);

Output:

1647415855771

What Is Math Object in JavaScript

The JavaScript math object offers several constants and methods to perform a mathematical operation on numbers.

  • Math.abs() – returns the absolute value of a number.
  • Math.round() – rounds a number to the nearest integer.
  • Math.ceil() – rounds a number up to the nearest integer.
  • Math.floor() – rounds a number down to the nearest integer.
  • Math.max() – returns the highest value in a list of numbers.
  • Math.min() – returns the lowest value in a list of numbers.
  • Math.random() – returns a random number between 0 and 1.

Example of math object codes:

// returns the absolute value of -5
Math.abs(-5);

// rounds 3.4 to 3 and 3.5 to 4
Math.round(3.4);
Math.round(3.5);

// rounds 3.1 to 4
Math.ceil(3.1);

// rounds 3.9 to 3
Math.floor(3.9);

// returns the highest value in the list of numbers
Math.max(5, 7, 2, 9, 4);

// returns the lowest value in the list of numbers
Math.min(5, 7, 2, 9, 4);

// returns a random number between 0 and 1
Math.random();

What Is throw Statement in JavaScript

The throw statement is used to throw an exception explicitly from your JavaScript code. You can use this statement to create custom error messages or to handle errors in your own way.

Here’s an example of using a throw statement code:

function divide(a, b) {
  if (b === 0) {
    throw new Error('Cannot divide by zero');
  }
  return a / b;
}

try {
  const result = divide(10, 0);
} catch (error) {
  console.log('An error occurred:', error.message);
}

In this example, we define a divide function that checks if the second argument b is 0. If b is 0, we throw a new Error with a custom message.

We catch the exception in the try-catch block and log the error message to the console.

What Is continue Statement in JavaScript

The continue statement in JavaScript is used to skip over a certain iteration of a loop and move on to the next iteration. This is useful when you want to skip over certain items in an array or object.

Here’s an example of using continue statement code:

// iterate over an array and skip over even numbers
const numbers = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < numbers.length; i++) {
  if (numbers[i] % 2 === 0) {
    continue;
  }
  console.log(numbers[i]); // logs 1, 3, 5, 7, 9
}

What Is slice() Method in JavaScript

The slice() method in JavaScript is used to extract a portion of an array and returns a new array containing the extracted elements. It takes two arguments, start and end, which specifies the beginning and end of the slice to be extracted.

The start index is inclusive, while the end index is exclusive. If end is not specified, the slice includes all elements from the start to the end of the array.

Here’s an example of using slice() method:

const fruits = ['apple', 'banana', 'orange', 'kiwi', 'grape'];
const slicedFruits = fruits.slice(1, 4);

console.log(slicedFruits); // ['banana', 'orange', 'kiwi']

In this example, the slice method is called on the fruits array with arguments of 1 and 4, which extracts the second, third, and fourth elements of the array and returns a new array containing those elements.

What Is concat() Method in JavaScript

The concat() method in JavaScript is used to combine two or more arrays into a single array. It takes one or more arrays as arguments and returns a new array that contains all the elements of the original arrays.

Here’s an example of using concat() method:

const arr1 = ['a', 'b', 'c'];
const arr2 = ['d', 'e', 'f'];
const arr3 = ['g', 'h', 'i'];

const concatenatedArray = arr1.concat(arr2, arr3);

console.log(concatenatedArray); // ['a', 'b', 'c', 'd', 'e', 'f', 'g', 'h', 'i']

In this example, the concat method is called on the arr1 array with arguments of arr2 and arr3, which combines all three arrays into a new array containing all the elements.

What Is reverse() Method in JavaScript

The reverse() method in JavaScript is used to reverse the order of elements in an array. It modifies the original array in place and returns a reference to the same array.

Here’s an example of using reverse() method:

const numbers = [1, 2, 3, 4, 5];
numbers.reverse();

console.log(numbers); // [5, 4, 3, 2, 1]

In this example, the reverse method is called on the numbers array, which reverses the order of elements in the array. The modified array is then logged to the console, showing the new order of elements.

What Is pop() Method in JavaScript

The pop() method removes the last element from an array and returns that element. It modifies the original array and reduces its length by one.

Here’s an example of using pop() method:

let fruits = ['apple', 'banana', 'orange'];
let lastFruit = fruits.pop(); // removes 'orange' and returns it
console.log(fruits); // output: ['apple', 'banana']
console.log(lastFruit); // output: 'orange'

What Is shift() Method in JavaScript

The shift() method removes the first element from an array and returns that element. It modifies the original array and reduces its length by one.

Here’s an example of using shift() method:

let fruits = ['apple', 'banana', 'orange'];
let firstFruit = fruits.shift(); // removes 'apple' and returns it
console.log(fruits); // output: ['banana', 'orange']
console.log(firstFruit); // output: 'apple'

What Is unshift() Method in JavaScript

The unshift() method adds one or more elements to the beginning of an array and returns the new length of the array. It modifies the original array.

Here’s an example of using unshift() method:

let fruits = ['banana', 'orange'];
let newLength = fruits.unshift('apple', 'kiwi'); // adds 'apple' and 'kiwi' to the beginning of the array
console.log(fruits); // output: ['apple', 'kiwi', 'banana', 'orange']
console.log(newLength); // output: 4

What Is includes() Method in JavaScript

The includes() method checks if an array includes a certain value, and returns a boolean (true or false) value accordingly.

Here’s an example of using includes() method:

let fruits = ['apple', 'banana', 'orange'];
let hasBanana = fruits.includes('banana'); // returns true
let hasGrapes = fruits.includes('grapes'); // returns false
console.log(hasBanana); // output: true
console.log(hasGrapes); // output: false

What Is join() Method in JavaScript

The join() method creates a string by concatenating all the elements of an array, separated by a specified separator (which is a comma by default).

Here’s an example of using join() method:

let fruits = ['apple', 'banana', 'orange'];
let fruitString = fruits.join(', '); // joins elements with a comma and space
console.log(fruitString); // output: 'apple, banana, orange'

What Is splice() Method in JavaScript

The splice() method is used to add or remove elements from an array. It takes three arguments: the index at which to start changing the array, the number of elements to remove (0 if you’re only adding elements), and the new elements to add (if any).

Here’s an example of using splice() method:

let fruits = ['apple', 'banana', 'orange'];
fruits.splice(1, 1, 'grapes', 'kiwi'); // removes 'banana' and adds 'grapes' and 'kiwi' at index 1
console.log(fruits); // output: ['apple', 'grapes', 'kiwi', 'orange']

What Is push() Method in JavaScript

The push() method adds one or more elements to the end of an array and returns the new length of the array.

Here’s an example of using push() method:

let fruits = ['apple', 'banana', 'orange'];
let newLength = fruits.push('grapes', 'kiwi'); // adds 'grapes' and 'kiwi' to the end of the array
console.log(fruits); // output: ['apple', 'banana', 'orange', 'grapes', 'kiwi']
console.log(newLength); // output: 5
Conclusion

Preparing for a JavaScript interview can be daunting, but it’s an essential step in your career as a developer. By familiarizing yourself with these common JavaScript interview questions, you’ll be better equipped to showcase your knowledge and skills in your next interview.

Remember to not just memorize the answers to these questions, but also to understand the concepts behind them, so you can apply them in real-world situations. With dedication and practice, you’ll be well on your way to becoming a confident and competent JavaScript developer.

If you read this far, tweet to the author to show them you care. Tweet a thanks
I am a computer scientist with a bias for data science, system management, and technical content development. My experience in the profession dates back to 2015. I read novels, jog, or play table tennis whenever I am not on gadgets.

Each tutorial at GeeksVeda is created by a team of experienced writers so that it meets our high-quality standards.

Join the GeeksVeda Weekly Newsletter (More Than 5,467 Programmers Have Subscribed)
Was this article helpful? Please add a comment to show your appreciation and support.

Got Something to Say? Join the Discussion...