// javascript {constx=1{constx=2// no error{console.log(x)// 2constx=3console.log(x)// 3}}}console.log(x)// undefined
In javascript, const denotes a read-only variable. If you try to reassign it, you'll get a "SyntaxError: Identifier has already been declared"
However, each braced segment is treated as a new scope. This is most obvious with functions and control structures like if (true) { ... }, but it's not immediately obvious to people that you can arbitrarily create new scopes anywhere. Switch statements are a good place to use them.
I've been a professional C, Perl, PHP and Python developer.
I'm an ex-sysadmin from the late 20th century.
These days I do more Javascript and CSS and whatnot, and promote UX and accessibility.
Const doesn't denote read-only, it only means you can't reassign it in the same scope. You can mutate it all you want (provided it's a type that's mutable in the first place)
In javascript,
const
denotes a read-only variable. If you try to reassign it, you'll get a "SyntaxError: Identifier has already been declared"However, each braced segment is treated as a new scope. This is most obvious with functions and control structures like
if (true) { ... }
, but it's not immediately obvious to people that you can arbitrarily create new scopes anywhere. Switch statements are a good place to use them.Wow, thanks for the hint !
Const doesn't denote read-only, it only means you can't reassign it in the same scope. You can mutate it all you want (provided it's a type that's mutable in the first place)
I worded it a bit slopy, a "read-only reference to a value" according to MDN, but it's all semantics as long as we understand how it works =]