0
JavaScript arrow functions with and without const
test = (x,y) => {} vs const test = (x,y) => {} In SoloLearn js course, arrow functions are always used with const but they also work without it. So what is the difference?
6 Respostas
+ 6
Aaron Eberhardt
Great explanation but I'd like to correct something: when not using a keyword var WILL NOT be inserted by the interpreter.
Actually the interpreter makes a global variable as a property of the global object (window in our case)
window.test = (x,y) => {}
https://code.sololearn.com/WIZ01zj1eZsM/?ref=app
Prof. Dr. Zoltán Vass
For that reason NEVER define a variable without keyword (var let const)
+ 3
Prof. Dr. Zoltán Vass sry, I didn't read the question correctly.
Not using any keyword is basically syntactically wrong, at least in strict mode. Most JS engines will automatically convert
test = () => {}
to
var test = () => {}
More correct would be the good old function declaration:
function test() {}
However with const and let functions are scoped otherwise they are global or semi scoped when using var. Sadly JS is a bit messed up due to some bad decisions and maintaining comparability so it's a bit hard to summarise all differences.
But to summarise all points use
function name() {...}
for global functions that should be accessible everywhere,
const name = () => {...}
for functions that operate in a certain scope or that are only needed in a certain scope and use
let name = () => {...}
for functions you want to reassign later.
+ 3
Aaron Eberhardt Very clear and detailed explanation, I appreciate it very much!
I tested the code in a mobile console (I have only a smartphone by me now) and it accepted the declaration without var or const - perhaps this caused the confusion.
+ 3
Prof. Dr. Zoltán Vass yes that's right. Not using a keyword will usually work on most browser. As I said a 'var' will be inserted by the interpreter. But that's just tolerated in order to maintain comparability with old web sites. If you use strict mode by writing
'use strict';
at the top of you document the interpreter won't accept that. The strict mode enforces the syntax a lot more and also runs faster because the code can be better optimised.
+ 2
Aaron Eberhardt Thanks Aaron! It also works without var (without anything before the function name). Could you also explain the difference between them?
+ 2
As was said, if do not write then the interpreter write the „var“ for you.