JavaScript Interview Questions(2025)

author image Hirely
at 05 Jan, 2025

Question: What are arrow functions in JavaScript?

Answer:

Arrow functions are a more concise syntax for writing functions in JavaScript. Introduced in ES6 (ECMAScript 2015), they provide a shorter way to define functions, but also come with some differences compared to traditional function expressions. Syntax of Arrow Functions:

const functionName = (parameters) => {
  // function body
};
  • parameters : The list of parameters the function accepts. If there is only one parameter, parentheses can be omitted.

  • => : The arrow syntax used to define the function.

  • {} : The body of the function, where the logic is written. If the function has a single expression, you can omit the curly braces and the return keyword. Examples: 1. Basic Arrow Function (Single Parameter)

const greet = name => {
  return `Hello, ${name}!`;
};

console.log(greet('John'));  // Hello, John!
  • Explanation : Here, name => { return ... } is an arrow function. It takes one parameter (name) and returns a greeting. 2. Arrow Function (Multiple Parameters)
const add = (a, b) => {
  return a + b;
};

console.log(add(2, 3));  // 5
  • Explanation : This function takes two parameters a and b, and returns their sum. 3. Implicit Return (Single Expression)
const multiply = (x, y) => x * y;

console.log(multiply(3, 4));  // 12
  • Explanation : If the function consists of a single expression, the curly braces and return keyword can be omitted. The result of the expression is implicitly returned. 4. No Parameters
const sayHello = () => console.log('Hello World');

sayHello();  // Hello World
  • Explanation : When there are no parameters, you can simply use () => to define an arrow function.

Key Differences Between Arrow Functions and Regular Functions:

  1. Syntax :
  • Arrow function : More concise and requires less boilerplate.

  • Regular function : Uses the function keyword and requires function declaration. Example:

// Arrow function
const greet = name => `Hello, ${name}!`;

// Regular function
function greet(name) {
  return `Hello, ${name}!`;
}
  1. this Behavior :
  • Arrow functions do not have their own this. Instead, they inherit this from the surrounding lexical context (where the function is defined). This is known as lexical scoping of this.

  • Regular functions have their own this, which is determined by how the function is called. **this Behavior :

  • Arrow functions do not have their own this. Instead, they inherit this from the surrounding lexical context (where the function is defined). This is known as lexical scoping of this.

  • Regular functions have their own this, which is determined by how the function is called. Example of this behavior:**

function regularFunction() {
  console.log(this);  // Refers to the object or global object depending on the call
}

const arrowFunction = () => {
  console.log(this);  // Inherits `this` from the surrounding context
};

In an object context:

const obj = {
  name: 'John',
  greet: function() {
    setTimeout(function() {
      console.log(this.name);  // `this` refers to the global object or undefined in strict mode
    }, 1000);
  }
};

obj.greet();  // Will print `undefined` or cause an error in strict mode

// Using arrow function
const objWithArrow = {
  name: 'John',
  greet: function() {
    setTimeout(() => {
      console.log(this.name);  // `this` refers to `objWithArrow`
    }, 1000);
  }
};

objWithArrow.greet();  // Will correctly print 'John'

Explanation :

  • In the first example, this inside the setTimeout function refers to the global object (or undefined in strict mode).

  • In the second example, using an arrow function inside setTimeout keeps the lexical context of this, referring to the objWithArrow object.

  1. arguments Object :
  • Arrow functions do not have their own arguments object. They inherit arguments from the surrounding scope.

  • Regular functions have their own arguments object, which contains all the arguments passed to the function. Example:

function regularFunction() {
  console.log(arguments);  // Logs all arguments passed to the function
}

const arrowFunction = () => {
  console.log(arguments);  // Inherits `arguments` from outer scope, or results in a ReferenceError
};

regularFunction(1, 2, 3);  // [1, 2, 3]
arrowFunction(1, 2, 3);    // ReferenceError: arguments is not defined
  1. Use as Methods :
  • Arrow functions should generally not be used as methods inside objects because they don’t have their own this.

  • Regular functions are ideal for defining methods where this refers to the object. Example:

const obj = {
  name: 'John',
  greet: function() {
    console.log(this.name);  // Correct `this`
  },
  greetArrow: () => {
    console.log(this.name);  // `this` does not refer to `obj`
  }
};

obj.greet();        // John
obj.greetArrow();   // undefined (arrow function's `this` doesn't refer to `obj`)

When to Use Arrow Functions:

  1. Shorter Syntax : Arrow functions are great for simple, short functions, especially when you don’t need the function’s own this or arguments.

  2. Callbacks : They are often used in situations where functions are passed as arguments, such as in array methods (map, filter, reduce, etc.), event handlers, or promises.Example with Array Methods :

const numbers = [1, 2, 3, 4];
const squares = numbers.map(num => num * num);
console.log(squares);  // [1, 4, 9, 16]
  1. Lexical this Binding : Arrow functions are helpful when you need to retain the value of this from the outer scope, such as in event handlers or inside methods that use asynchronous code like setTimeout or promises.

Summary:

  • Arrow functions offer a concise syntax and have no own this, making them ideal for situations where this should be lexically bound.

  • They cannot be used as methods when the this binding is required for the object.

  • Regular functions are more flexible, with their own this and arguments, making them suitable for method definitions and functions that need to handle parameters dynamically.

Question: What is the difference between a function expression and a function declaration in JavaScript?

Answer:

In JavaScript, there are two main ways to define a function: function declarations and function expressions . While both allow you to define a function, they differ in their syntax, behavior, and when they are available for use.1. Function Declaration A function declaration defines a named function that is available for use in the scope it was declared, typically at the time of its declaration (hoisting).Syntax:

function functionName(parameters) {
  // function body
}
  • Hoisting : Function declarations are hoisted . This means that the function is available throughout the scope, even before the point of its declaration.

  • Named Function : Function declarations must have a name.

  • Global Scope : When declared at the global level, the function becomes globally accessible. Example:

// Function Declaration
function greet(name) {
  return `Hello, ${name}!`;
}

console.log(greet('John'));  // Hello, John!
  • Hoisting Behavior : Function declarations are hoisted to the top of the scope, so you can call the function before it is defined in the code:
console.log(greet('Alice'));  // Hello, Alice!

function greet(name) {
  return `Hello, ${name}!`;
}

This works because the function declaration is hoisted to the top.


2. Function Expression A function expression involves creating a function and assigning it to a variable. The function can be either anonymous (without a name) or named, but it is not hoisted like a function declaration.Syntax:

const functionName = function(parameters) {
  // function body
};
  • Not Hoisted : Function expressions are not hoisted . This means the function is not available until the code execution reaches the point where the function is assigned.

  • Anonymous or Named : You can define anonymous functions (functions without names) or named functions as function expressions.

  • Assigned to Variables : The function is assigned to a variable, which can be used to call the function. Example:

// Function Expression (Anonymous)
const greet = function(name) {
  return `Hello, ${name}!`;
};

console.log(greet('John'));  // Hello, John!
  • Hoisting Behavior : Function expressions are not hoisted , so calling the function before its definition will result in an error:
console.log(greet('Alice'));  // TypeError: greet is not a function

const greet = function(name) {
  return `Hello, ${name}!`;
};

In this case, the variable greet is hoisted (but with an undefined value), and the function assignment occurs only when the code reaches that line.


Key Differences Between Function Declarations and Function Expressions: | Feature | Function Declaration | Function Expression | | --- | --- | --- | | Syntax | function name() {} | const name = function() {} | | Hoisting | Hoisted (available before declaration) | Not hoisted (available after definition) | | Assignment | Not assigned to a variable | Assigned to a variable | | Anonymous | Must have a name | Can be anonymous or named | | Scope | Available throughout the scope | Available only after the expression is evaluated | | Usage in Callbacks | Less common for callbacks (due to hoisting) | Common for callbacks, especially anonymous ones |


Examples of Function Declarations and Expressions: 1. Function Declaration Example:

function add(a, b) {
  return a + b;
}

console.log(add(5, 3));  // 8
  • The function add can be called before or after its declaration because function declarations are hoisted. 2. Function Expression Example:
const multiply = function(a, b) {
  return a * b;
};

console.log(multiply(5, 3));  // 15
  • The function multiply can only be called after its assignment. If you try to call it before the assignment, you’ll get an error. 3. Anonymous Function Expression Example (for callbacks):
setTimeout(function() {
  console.log('Hello after 2 seconds');
}, 2000);
  • This example uses an anonymous function expression as a callback function. 4. Named Function Expression Example:
const factorial = function fact(n) {
  if (n === 0) return 1;
  return n * fact(n - 1);
};

console.log(factorial(5));  // 120
  • Here, fact is a named function expression. While fact can be used within the function, the variable factorial is the one used to invoke the function.

Summary:

  • Function Declarations are hoisted, so they can be called before they are defined.

  • Function Expressions are not hoisted, so they can only be called after the expression is evaluated.

  • Function Declarations are typically used when you need a function to be available throughout the scope, while Function Expressions are more commonly used when assigning functions to variables, especially for anonymous functions or callbacks.

Read More

If you can’t get enough from this article, Aihirely has plenty more related information, such as JavaScript interview questions, JavaScript interview experiences, and details about various JavaScript job positions. Click here to check it out.

Related Posts

Trace Job opportunities

Hirely, your exclusive interview companion, empowers your competence and facilitates your interviews.

Get Started Now