DEV Community

Discussion on: Share a code snippet in any programming language and describe what's going on

Collapse
 
crowdozer profile image
crowdozer
// javascript 

{
  const x = 1
  {
    const x = 2 // no error
    {
      console.log(x) // 2
      const x = 3 
      console.log(x) // 3
    }
  }
}

console.log(x) // undefined
Enter fullscreen mode Exit fullscreen mode

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.

Collapse
 
pothieug profile image
Gilles Pothieu

Wow, thanks for the hint !

Collapse
 
moopet profile image
Ben Sinclair

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)

const x = [1, 2, 3];

x.push(4);
delete x[0];

// [ <empty slot>, 2, 3, 4 ]
Enter fullscreen mode Exit fullscreen mode
Collapse
 
crowdozer profile image
crowdozer • Edited

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 =]