Why declare "let" outside of a block?


#1

I’ve looked through w3schools and other resources, and I can not find a purpose to using ‘let’ outside of a block. When you are outside of a block, why not just code:

x = 5;

rather than:

let x = 5;

If dealing with lengthy code/big data, would declaring let outside of a block perform the same, or would it be slower? Why not just go with the former usage when “let” does not have a functional difference outside of a block?


#2

There are differences, but the differences are subtle.

But to truly understand this issue, you need to understand the different between es5 and es6. Programming languages get updates like other pieces of software. You use es6 (the 6th “edition”), let was introduced in es6. Lets first go back to es5

in es5, there was var (let and const didn’t exist). So then first you would have to understand the differences between var x = 5 and x = 5:

https://stackoverflow.com/questions/1470488/what-is-the-purpose-of-the-var-keyword-and-when-should-i-use-it-or-omit-it/1471738#1471738

its a pity this answer is so old, but its still sort of relevant, then you need to understand the difference between var and let:

https://stackoverflow.com/questions/39414692/a-javascript-let-global-variable-is-not-a-property-of-window-unlike-a-global

it goes quite in depth of the language, so see you what you can make of it.

Otherwise leave it for now, and come back later, once you understanding has improved.

For now, i would advise you to use var


#3

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