+ 1

var is useless?

I've done a fair bit of reading about var, let, and const. One article I read said this: "A commonly accepted practice is to use const as much as possible, and let in the case of loops and reassignment. Generally, var can be avoided outside of working on legacy code." My question: - do you avoid using var now that let and const have come? - what are some of the reasons to not use var? My hunch is that 1) it can have issues because of hoisting and 2) it uses more memory (or maybe uses memory differently??) - are there any use cases you can think of to use var? (apart from legacy code)

27th Mar 2018, 12:41 PM
dCook
dCook - avatar
3 Antworten
+ 3
Not useless if it was why was it added in the 1st place! I use const when I know the value won't be reassigned or changed for most part' let I use when block scoped variable is desired like in for loops or local variables limited to some code inside curly braces{}. var I use when I need a function scope variable or if I need to reassign the value for some reason.. So I use them according to the requirement. if reassignment or function scope is to be avoided like in for loops don't use var.
27th Mar 2018, 1:08 PM
Lord Krishna
Lord Krishna - avatar
+ 2
1-`const` is a signal that the identifier won’t be reassigned. `var` is now the weakest signal available when you define a variable in JavaScript. The variable may or may not be reassigned, and the variable may or may not be used for an entire function, or just for the purpose of a block or loop. 2-https://hackernoon.com/why-you-shouldnt-use-var-anymore-f109a58b9b70 3-https://softwareengineering.stackexchange.com/questions/274342/is-there-any-reason-to-use-the-var-keyword-in-es6
27th Mar 2018, 12:45 PM
Baraa AB
Baraa AB - avatar
+ 1
Thanks for your input! It seems like var really is kind of unnecessary. @Lord Krishna, yes it seems like function-scope would be good to keep in mind for var. However, declaring a let variable at the outset of a function gives it function wide scope I believe... (not sure about nested functions though. function myFunc() { let a = 10; // function-scope! if (a) { console.log("a:", ++a); let b = 10; } console.log("b:", b); //nope! } myFunc();
27th Mar 2018, 2:43 PM
dCook
dCook - avatar