Just getting back into a bit of javascript. Looking at recent coding I am seeing ‘const’ and ‘let’ being used a lot. All variable declaration replaced with ‘let’ and even large functions/modules being assigned to ‘const’.
I get the gist of these declarations, ‘let’ gives you block-scope and const is used for constants e.g. const PI = 3.142 (Something that isn’t going to change). My question is what is the best practice for using these? Should they not be limited to specific use?
One of my first thoughts was that if you didn’t need or want a variable to be referenced via the scope-chain you could use ‘let’, but was surprised to see the following result in a test. (In php I believe you would have to use ‘global’ or pass x into the inner function)
var testLet = function(){
let x = 10
return function(){
console.log(x)
}
}
testLet()() // 10?
[quote=“rpg_digital, post:1, topic:286929, full:true”]
My question is what is the best practice for using these? Should they not be limited to specific use?[/quote]
You can get away with using var for function scope, but if you use let/const for block scope it’s safer to use const as much as you can. Good programming technique shouldn’t result in needing to reassign back to the same variable name at all.
By using const as a good habit, when you do see the occasional rare let it serves as a warning to you, that this variable is going to change at some stage.
Crossed wires, I do know about closure, function invocation, hoisting, variable/activation objects etc.
I was just interested to see if ‘let’ was unique in that it prevented X from being referenced from the inner function via the scope chain. In other words access was limited to just the outer function block it was declared in. (Similar to PHP from what I have seen)