Understanding the typeof Operator for Function Parameters with the Rest Operator. Tech Mahindra interview question. Javascript interview prepration.


Understanding the Code Step by Step

The given JavaScript snippet uses the rest parameter (...ages) inside a function and checks its data type using typeof. Let’s break it down carefully.


Javascript Code:

function getAge(...ages) {
console.log(typeof ages); } getAge(25);

Step 1: Understanding the ...ages (Rest Parameter)

  • The rest parameter (...ages) allows the function to accept multiple arguments and collect them into a single array.
  • Even if only one argument (25) is passed, ages will still be an array.

    What Happens When getAge(25) is Called?

getAge(25);

  • The function receives 25 as an argument.
  • Because of the rest parameter, ages becomes:

ages = [25]; // An array containing a single element

Step 2: Evaluating typeof ages

Inside the function:

console.log(typeof ages);

  • Since ages is an array, JavaScript treats it as an object.
  • In JavaScript, arrays are a type of object, so:

typeof ages // → "object"

Step 3: Console Output

object

Final Output

object

Remember key points:

  1. Rest parameters (...args) always return an array, even if there’s only one argument.
  2. typeof an array always returns "object", because arrays are a subtype of objects in JavaScript.
  3. If you need to check whether a variable is specifically an array, use:
    1. console.log(Array.isArray(ages)); // true
  4. Even with zero arguments, ages will be an empty array ([]).
    1. getAge(); // ages = [], typeof ages = "object"


✔ Final Answer:

C) object

This question appeared in the Tech Mahindra 2nd round of interview, testing the candidate’s knowledge of function parameter, rest operator and the typeof operator in JavaScript.

Post a Comment

Previous Post Next Post