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:
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?
-
The function receives
25
as an argument. - Because of the rest parameter,
ages
becomes:
Step 2: Evaluating typeof ages
Inside the function:
-
Since
ages
is an array, JavaScript treats it as an object. - In JavaScript, arrays are a type of object, so:
Step 3: Console Output
Final Output
Remember key points:
- Rest parameters (
...args
) always return an array, even if there’s only one argument. typeof
an array always returns"object"
, because arrays are a subtype of objects in JavaScript.- If you need to check whether a variable is specifically an array, use:
- console.log(Array.isArray(ages)); // true
- Even with zero arguments,
ages
will be an empty array ([]
). - 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.