This is what Jayesh Bhoot looks like, with a lopsided smile on its right, which almost closes his right eye while smiling, which strongly implies that he needs to work on his lazy left-side cheek muscles.

JavaScript function declaration v/s arrow function in a browser console

Posted on

Collected in

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

Post author's photo Written by Jayesh Bhoot

Comments