This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
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.
This content originally appeared on DEV Community and was authored by Coderslang: Become a Software Engineer
Coderslang: Become a Software Engineer | Sciencx (2021-06-07T13:20:21+00:00) JavaScript Interview Question #46: Length of JS functions. Retrieved from https://www.scien.cx/2021/06/07/javascript-interview-question-46-length-of-js-functions/
Please log in to upload a file.
There are no updates yet.
Click the Upload button above to add an update.
