real use of {const} and issues

# Fyodorov "Bga" Alexander (14 years ago)

my view of {const} keyword semantic

  1. alloced 1 time, as {var}, for correct work of closure
  2. assign w/o {const} redeclaration - (not silent) error
  3. assign w/ {const} redeclaration - change value and small code, reason

var i = vs.length; while(i--) { const v = vs[i] // one alloc but many assigns v = 1 // assign w/o {const} keyword - error }

# Brendan Eich (14 years ago)

On May 31, 2011, at 4:32 AM, Fyodorov Bga Alexander wrote:

my view of {const} keyword semantic

  1. alloced 1 time, as {var}, for correct work of closure
  2. assign w/o {const} redeclaration - (not silent) error
  3. assign w/ {const} redeclaration - change value

That's what SpiderMonkey has done, since a long time ago:

js> vs=[1,2,4,8] [1, 2, 4, 8] js> var i = vs.length; while(i--) { const v = vs[i] // one alloc but many assigns v = 1 // assign w/o {const} keyword - error } 1 js> "use strict" "use strict" js> var i = vs.length; while(i--) { const v = vs[i] // one alloc but many assigns v = 1 // assign w/o {const} keyword - error } typein:10: TypeError: redeclaration of const v

and small code, reason

var i = vs.length; while(i--) { const v = vs[i] // one alloc but many assigns v = 1 // assign w/o {const} keyword - error }

What's the "reason"? This code example does not contain a rationale.

The ES.next plan for const is like let, block scoped, but write-once, error to read before that initial write (which requires a read barrier, static analysis can help but the full semantics are a "temporal dead zone" before initialization -- see esdiscuss/2008-October/007807).