+ 3

Var vs Let

When would you use var and when would you use let and why?

4th Oct 2017, 3:40 PM
Daniel Prodrick
Daniel Prodrick - avatar
3 Respostas
+ 7
Basically: don't use var unless you have to support old browsers. The differences are pretty subtle. For example, the main reason we got let in the new Javascript versions is "hoisting". Calling this function let_test(){ alert(x); let x = 4; } will error (as it should) with "x is not defined". Calling this function var_test(){ alert(x); var x = 4; } will alert "undefined", because due to hoisting, the function will be transformed to function var_test_after_hoisting(){ var x; console.log(x); x = 4; } So all variables you declare with var will be hoisted to the top of the function, which is a bit silly. No other language behaves this way, and it has led to many a bug! Also, as Zephyr was saying, let is block-scoped and var is function-scoped. so function var_test(){ var x = 4; if(...){ var x = 5; // this is the same x alert(x); } alert(x); } will alert 5, then 5, and function let_test(){ let x = 4; if(...){ let x = 5; // different x alert(x); } alert(x); } will alert 5, then 4. Those are the main differences, there are a few other ones though, too. so, basically... let is an attempt to make variables behave more like they do in other languages, and odd var behaviour is a remnant of the 90s.
4th Oct 2017, 4:14 PM
Schindlabua
Schindlabua - avatar
+ 9
I believe let have smaller scope compared to var and it's a recent JavaScript feature. You can Google for it or I'll let the JS expert here to answer your question. 😉
4th Oct 2017, 3:45 PM
Zephyr Koo
Zephyr Koo - avatar
+ 4
that is such a great answer thank you for your detailed response :) i feel as though i should go through my old code now and change all the vars to lets haha. And i agree that variable hoisting is very strange it confused me when i first saw a variable being hoisted in js i am playing in the console now and testing var and let scope and hoisting etc
4th Oct 2017, 4:22 PM
Daniel Prodrick
Daniel Prodrick - avatar