javascript interview question #46

What’s the value of the length field for JavaScript functions? What will be logged to the console?

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

.

A lot of JavaScript entities have the length field.

For example, it holds the total number of element in JavaScript arrays.

const arr = ['a', 'b', 'c'];
console.log(arr.length);    // 3

For strings — it’s the number of characters. Literally, the length of a string.

const welcomeMessage = 'Hello!';
const goodbyeMessage = 'Goodbye!';
const emptyString = '';

console.log(welcomeMessage.length);  // 6
console.log(goodbyeMessage.length);  // 8
console.log(emptyString.length);     // 0

Regular objects don’t have the length field by default.

const user = { name: 'Jack', age: '32'};
console.log(user.length);  // undefined

But the functions do have it! And it holds not the “length of a function”, which is hard to define, but rather the number of function parameters.

const sum = (a, b) => a + b;
const log = (s) => console.log(s);
const noop = () => {};

console.log(sum.length);  // 2
console.log(log.length);  // 1
console.log(noop.length); // 0

ANSWER: The length field holds the number of parameters for all JavaScript functions. Thus, the output is

0
1

As the function sayHello has one parameter and the function confirmSubscription has zero parameters.