JavaScript interview questions with code examples

JavaScript interview questions with code examples

closure in JavaScript

What is closure in JavaScript and how can it be used to create private variables?

A closure is a function that has access to variables in its outer scope, even after the outer function has returned. Closures can be used to create private variables in JavaScript by returning an inner function that has access to the variables declared in the outer function. Here’s an example:

function createCounter() {

  let count = 0;

  return function() {

    count++;

    return count;

  };

}

const counter = createCounter();

console.log(counter());  // 1

console.log(counter());  // 2

console.log(counter());  // 3

In this example, the createCounter function declares a private variable count and returns an inner function that increments count every time it’s called. The returned inner function has access to the count variable even after the createCounter function has returned, allowing it to maintain its value between invocations.

hoisting in JavaScript

What is hoisting in JavaScript and how does it work?

Hoisting is a behavior in JavaScript where variable and function declarations are moved to the top of their scope. This means that variables can be used before they are declared, and functions can be called before they are defined. Here’s an example:

console.log(x);  // undefined

var x = 10;

In this example, even though the x variable is declared after it is used, the JavaScript engine hoists the declaration to the top of the scope, so the code runs as if it were written like this:

var x;

console.log(x);  // undefined

x = 10;

Hoisting also applies to function declarations:

myFunction();  // “Hello, World!”

function myFunction() {

  console.log(“Hello, World!”);

}

In this example, the function declaration for myFunction is hoisted to the top of the scope, so it can be called before it is defined.

difference between null and undefined in JavaScript

What is the difference between null and undefined in JavaScript?

In JavaScript, null and undefined are both values that represent the absence of a value. However, there is a subtle difference between the two.

undefined is a value that is automatically assigned to a variable when it is declared but not assigned a value:

let x;

console.log(x);  // undefined

null, on the other hand, is a value that must be explicitly assigned to a variable:

let y = null;

console.log(y);  // null

In other words, undefined is a default value assigned to a variable when no value is explicitly assigned, while null is a value that can be explicitly assigned to represent the absence of a value.

difference between a for loop and forEach in JavaScript

What is the difference between a for loop and forEach in JavaScript?

In JavaScript, both for loops and the forEach method are used to iterate over arrays. However, there are some key differences between the two.

for loops allow you to access the current index and value of each element in the array, and you can also use break and continue statements to control the flow of the loop:

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

for (let i = 0; i < numbers.length; i++) {

  console.log(numbers[i]);

}

In this example, the for loop iterates over the numbers array, and the console.log statement logs the value of each element in the array.

The forEach method, on the other hand, is a higher-order function that is called on an array and takes a callback function as an argument. The callback function is invoked for each element in the array:

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

numbers.forEach(function(number) {

  console.log(number);

});

In this example, the forEach method is called on the numbers array, and the anonymous callback function logs the value of each element in the array.

The main difference between the two is that for loops offer more control over the flow of the loop, while forEach is a simpler and more concise way to iterate over an array.

difference between == and === in JavaScript

What is the difference between == and === in JavaScript?

In JavaScript, there are two comparison operators: == (loose equality) and === (strict equality).

The == operator performs type coercion before checking for equality, which means that it converts the operands to the same type before checking for equality:

console.log(1 == “1”);  // true

console.log(true == 1);  // true

In these examples, the == operator converts the string “1” to the number 1, and the boolean value true to the number 1, before checking for equality, so both expressions return true.

The === operator, on the other hand, does not perform type coercion and checks for equality without converting the operands to the same type:

console.log(1 === “1”);  // false

console.log(true === 1);  // false

In these examples, the === operator does not convert the string “1” or the boolean value true to the number 1, so both expressions return false.

It is generally recommended to use the === operator in JavaScript, as it ensures that equality is checked without any type coercion, leading to more predictable results.

Coding Function that returns a sum of the elements

Write a function that takes an array of numbers and returns the sum of its elements.

function sumArray(numbers) {

  let sum = 0;

  for (let i = 0; i < numbers.length; i++) {

    sum += numbers[i];

  }

  return sum;

}

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

console.log(sumArray(numbers));  // 15

In this example, the sumArray function takes an array of numbers as an argument and uses a for loop to iterate over the array, adding each element to the sum variable. The function returns the sum of the elements in the array.

Function that takes an array of strings returns string lengths 

Write a function that takes an array of strings and returns an array of the lengths of each string.

function stringLengths(strings) {

  let lengths = [];

  strings.forEach(function(string) {

    lengths.push(string.length);

  });

  return lengths;

}

const strings = [‘hello’, ‘world’, ‘foo’, ‘bar’];

console.log(stringLengths(strings));  // [5, 5, 3, 3]

In this example, the stringLengths function takes an array of strings as an argument and uses the forEach method to iterate over the array. For each string, the length is determined using the length property and pushed onto the lengths array. The function returns the array of lengths.

Function takes an array and returns a new array with only even numbers

Write a function that takes an array of numbers and returns a new array with only the even numbers.

function getEvenNumbers(numbers) {

  let evenNumbers = [];

  numbers.forEach(function(number) {

    if (number % 2 === 0) {

      evenNumbers.push(number);

    }

  });

  return evenNumbers;

}

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

console.log(getEvenNumbers(numbers));  // [2, 4]

In this example, the getEvenNumbers function takes an array of numbers as an argument and uses the forEach method to iterate over the array. For each number, the function checks if it is even by using the modulo operator % to check if the remainder of the division by 2 is 0. If the number is even, it is pushed onto the evenNumbers array. The function returns the array of even numbers.

Function that takes array of objects and returns specific property values

Write a function that takes an array of objects and returns an array of values of a specific property of each object.

function getPropertyValues(objects, property) {

  let values = [];

  objects.forEach(function(object) {

    values.push(object[property]);

  });

  return values;

}

const objects = [

  {name: ‘John’, age: 32},

  {name: ‘Jane’, age: 28},

  {name: ‘Jim’, age: 35}

];

console.log(getPropertyValues(objects, ‘name’));  // [‘John’, ‘Jane’, ‘Jim’]

In this example, the getPropertyValues function takes an array of objects and a property name as arguments and uses the forEach method to iterate over the array of objects

Function that returns largest number from the array

Write a function that takes an array of numbers and returns the largest number.

function findLargestNumber(numbers) {

  let largest = numbers[0];

  for (let i = 1; i < numbers.length; i++) {

    if (numbers[i] > largest) {

      largest = numbers[i];

    }

  }

  return largest;

}

const numbers = [1, 5, 10, 3, 20];

console.log(findLargestNumber(numbers));  // 20

In this example, the findLargestNumber function takes an array of numbers as an argument and uses a for loop to iterate over the array. The function initializes the largest variable to the first element of the array, and then iterates over the remaining elements, checking if each element is larger than the current largest value. If an element is larger, the largest variable is updated to that value. The function returns the largest number in the array.

Function returning array of objects and unique values

Write a function that takes an array of objects and returns an object with properties that correspond to the unique values of a specific property of each object.

function createObjectFromArray(objects, property) {

  let uniqueValues = {};

  objects.forEach(function(object) {

    uniqueValues[object[property]] = true;

  });

  return uniqueValues;

}

const objects = [

  {name: ‘John’, city: ‘New York’},

  {name: ‘Jane’, city: ‘London’},

  {name: ‘Jim’, city: ‘New York’}

];

console.log(createObjectFromArray(objects, ‘city’));

// {

//   New York: true,

//   London: true

// }

In this example, the createObjectFromArray function takes an array of objects and a property name as arguments and uses the forEach method to iterate over the array of objects. For each object, the value of the specified property is used as a key in the uniqueValues object, and the value is set to true. The function returns the uniqueValues object, which has properties that correspond to the unique values of the specified property in the array of objects.

Function that returns squares of array numbers

Write a function that takes an array of numbers and returns an array of the squares of each number.

function squareNumbers(numbers) {

  let squares = [];

  numbers.forEach(function(number) {

    squares.push(number * number);

  });

  return squares;

}

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

console.log(squareNumbers(numbers));  // [1, 4, 9, 16, 25]

In this example, the squareNumbers function takes an array of numbers as an argument and uses the forEach method to iterate over the array. For each number, the square is determined by multiplying the number by itself and the result is pushed onto the squares array. The function returns the array of squares.

Function that returns new string with specific occurrences removed

Write a function that takes a string and returns a new string with all occurrences of a specified character removed.

function removeCharacter(string, character) {

  let newString = ”;

 for (let i = 0; i < string.length; i++) {

    if (string[i] !== character) {

      newString += string[i];

    }

  }

  return newString;

}

const originalString = ‘Hello World’;

console.log(removeCharacter(originalString, ‘o’));  // ‘Hell Wrd’

In this example, the removeCharacter function takes a string and a character as arguments. The function uses a for loop to iterate over the characters in the string. If the current character is not equal to the specified character, it is concatenated onto the newString. The function returns the newString without the specified character.

Function returns new array of strings with 5 characters 

Write a function that takes an array of strings and returns a new array with all strings that have a length of exactly 5 characters.

function findStringsOfLength5(strings) {

  let stringsOfLength5 = [];

  strings.forEach(function(string) {

    if (string.length === 5) {

      stringsOfLength5.push(string);

    }

  });

  return stringsOfLength5;

}

const strings = [‘Hello’, ‘World’, ‘Five’, ‘Length’, ‘Words’];

console.log(findStringsOfLength5(strings));  // [‘Hello’, ‘Words’]

In this example, the findStringsOfLength5 function takes an array of strings as an argument and uses the forEach method to iterate over the array. For each string, the length is checked to see if it is equal to 5. If the length is 5, the string is pushed onto the stringsOfLength5 array. The function returns the stringsOfLength5 array, which contains all strings that have a length of exactly 5 characters.