Best practice for var, let and const


#1

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?

Thanks ahead


#2

That also works when using var, or const too for that matter.

How it works is that the inner function retains knowledge of its parent environment, and is a technique called closure.


#3

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.


#4

Hi Paul,

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)

No biggy, cheers


#5

Thanks Paul, I get what you are saying. I'm guessing const is also not a bad safe-guard for preventing accidental reassigning?

I will do some more reading up!!


closed #6

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.