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?

6th Mar 2020, 6:36 PM
Prof. Dr. ZoltĂĄn Vass
6 Answers
+ 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)
7th Mar 2020, 3:26 AM
Kevin ★
+ 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.
6th Mar 2020, 7:14 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 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.
6th Mar 2020, 7:21 PM
Prof. Dr. ZoltĂĄn Vass
+ 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.
6th Mar 2020, 7:27 PM
Aaron Eberhardt
Aaron Eberhardt - avatar
+ 2
Aaron Eberhardt Thanks Aaron! It also works without var (without anything before the function name). Could you also explain the difference between them?
6th Mar 2020, 7:05 PM
Prof. Dr. ZoltĂĄn Vass
+ 2
As was said, if do not write then the interpreter write the „var“ for you.
6th Mar 2020, 9:48 PM
JaScript
JaScript - avatar