Coderslang

Search IconIcon to open search

Variable number of arguments in JavaScript [Tech Interview Quiz]

Last updated Jan 8, 2023

JavaScript allows developers to define functions that can accept a variable number of arguments. This can be useful when the number of arguments that a function receives is not fixed or known beforehand.

To be comfortable with the functions that accept variable number of arguments in JavaScript, you need to know how to use the arguments object as well as the spread operator, which was introduced in ES6.

There’s also difference in how arrow functions and regular functions handle the arguments array.

Consider the following code snippet and find out what would the output be.

Code snippet as a picture

1
2
3
4
5
6
7
8
const args = [ 1, 2, 3 ];
const arrowFunction = (x, y) => {
  return (arguments[2]);
}
const regularFunction = function (x, y) {
  return (arguments[2]);
}
console.log(arrowFunction(...args), regularFunction(...args));

Are there any issues with the code? What’s going to be logged to the console? (think well, then click for the answer and explanation)

Explanation

In JS, all functions have access to the internal arguments array that holds all arguments that were passed into the function.

We can access the elements of this array by index, thus expecting that both regularFunction and arrowFunction will return true.

The only issue is that arrow functions don’t have access to the arguments array.

There might be two separate outcomes in line 8. Most likely you’ll see the message ReferenceError: arguments is not defined. However, there also might be a different scenario. For example, if you run this code in Node.js, arguments[2] is likely to be evaluated to something like

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
Module {
  id: '.',
  path: '/workdir_path',
  exports: {},
  parent: null,
  filename: '/workdir_path/scriptName.js',
  loaded: false,
  children: [],
  paths: [
    '/node_modules'
  ]
}

In which case, we’ll see false logged to the screen as 3 is not equal to the object described above.

Answer

false or ReferenceError will appear in the console depending on the execution environment

🔥 START LEARNING 🔥