JavaScript arrow functions with and without const | Sololearn: Learn to code for FREE!


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?

3/6/2020 6:36:47 PM

Prof. Dr. Zoltán Vass

6 Answers

New Answer


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) => {} Prof. Dr. Zoltán Vass For that reason NEVER define a variable without keyword (var let const)


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.


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.


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.


Aaron Eberhardt Thanks Aaron! It also works without var (without anything before the function name). Could you also explain the difference between them?


As was said, if do not write then the interpreter write the „var“ for you.