JavaScript function declaration v/s arrow function in a browser console
Collected in javascript
Apart from the usual conciseness and this
arguments, JavaScript's function declaration and arrow functions differ in another practical way.
I often like to develop and test small JavaScript code directly in a browser console.
In this environment, a function declaration has an advantage over an arrow function – I can re-define & re-run a function declaration repeatedly in a browser's console.
>> function strIdentity(v) {
return v.toUpperCase();
}
undefined
>> function strIdentity(v) {
return v.toLowerCase();
}
undefined
>> strIdentity("HELLO");
"hello"
On the other hand, re-running an arrow function, which have to be assigned to a variable to be usable at the top level, would throw a re-declaration error, because the same variable cannot be re-declared again.
>> const strIdentity = v => v.toLowerCase();
undefined
>> // editing the above script
>> const strIdentity = v => v.toUpperCase();
Uncaught SyntaxError: redeclaration of const strIdentity
Written by Jayesh Bhoot