0
Should I still use "var" or change to "let" to initialize objects?
Recently, it has been suggested to use "let" and discourage the use of "var" for initialization. What about for initializing objects?
5 Respostas
+ 4
https://www.sololearn.com/learn/JavaScript/2969/?ref=app
https://www.sololearn.com/post/39014/?ref=app
You'll find why let is preferred in the threads above. The same benefits apply for both primitives and objects.
The only difference between "let a=4" and "let a = {}" is the value assigned to the variable and its type, let keyword behaves the same way for them both, and so does var.
Notes:
Variables declared with var keyword are not global, but hoisted and available on its enclosing scope(global scope and function scope as examples).
const keyword prevents re-assignments but not mutations on the value holded, as @Avinesh said.
const a = 3
a = 42 // error
const b = { }
b.something = "wow" // it works
One of the reasons of still using var over let is backward compatibility:
https://www.sololearn.com/discuss/751459/?ref=app
If you are ok with that, then let's let.
\\Edited\\
+ 2
absolutely you must declare variables by either "let " or "const".
let => to declare variable in block scope and you can change its value later .
const => to declare a variable and you can't change its value later on
why dont use var ?
var for declaring variable in global scope, it can be accessible globaly , so its a bad idea , .
feel free to do a search for that
+ 1
For "var" and "let" and objects, why or why not to use either?
+ 1
You can use both 'let' and 'const' to initialize objects. But for objects the 'const' keyword doesn't work the way it should. It means that you can still modify the object properties. In that case you can use Object.freeze() to prevent any modification of properties.
+ 1
Avinesh const works precisely as it should.