Temp O'rary Temp O'rary - 1 month ago 12
Javascript Question

Value of 'arguments' of fat arrow function inside callback giving unexpected values

See the below snippets:

Snippet #1:



let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(arguments));








Snippet #2:


let fs = require("fs");
fs.readFile(process.argv[2], "utf8", (error, data) => console.log(error, data));








Expected log:
Values of
(error, data)
, for example like:

null 'console.log("HELLO WORLD");\r\n'





When you try both these snippets, you will find that the Snippet #1 executes and logs some unexpected values for
console.log(arguments)
but
console.log(error, data)
logs proper values; values of
(error, data)
.

Why and What was the value that is being logged for Snippet #1?

Answer

No binding of arguments

Arrow functions do not bind an arguments object Thus, arguments is simply a reference to the name in the enclosing scope.

From: MDN - Arrow functions

If you wish to use variadic arguments inside an arrow function, use the rest parameters syntax:

fs.readFile(process.argv[2], "utf8", (...args) => console.log(args));