Hacker News new | past | comments | ask | show | jobs | submit login

`const` means that the variable binding itself is immutable. It only affects the variable binding, not the value it points to.

If it affected the value it pointed to, what would happen in this type of situation?

    let x = {};
    const y = x;
    x.a = 5;



This is trivially testable in most browsers inspection tools.

The answer is it works fine. x.a === y.a === 5

This is because you are simply declaring the binding of y to the object bound to x constant. This does not impact your ability to rebind x or to alter the contents of the object, it simply prevents you from rebinding y.

    let x = {a:5}
    x = {}
    console.log(x.a) // undefined
---

    const y = {a:5}
    y = {} // Uncaught TypeError: Assignment to a constant variable.
---

    let x = {a:2}
    const y = x
    x.b = 12    
    x = {}
    x.b = 13
    console.log(y) // {a: 2, b:12}
    console.log(x) // {b: 13}


The question was rhetorical to try to demonstrate that it might result in surprising behavior if const just manipulated its values to make them become immutable. If adding the `const y = x;` line made the object referenced in `x` be immutable, then the 3rd line would fail, which I don't is a consequence desired even by people who thought const made things immutable.

I guess one alternative idea for how const would work could be an implementation where `x.a = 5` worked but `y.a = 5` failed. But then what happens if you pass `y` into a function which then tries to assign the `a` property on it? Is the const-ness part of the value passed into the function, or is it a property on variable bindings, and you could only pass `y` to functions that accepted a const variable? That kind of function type checking isn't something usual to javascript currently. And then is the const-ness deep? Is `y.foo.a = 5;` blocked? Mutable DOM elements are a big part of javascript. If the object happened to contain a reference to an element that needed to be manipulated, then you won't be able to do something like `y.foo.element.textContent = "new foo content";`. Going down this road it's now getting to be a pretty big feature that doesn't cleanly fit with the rest of the language or common tasks.

Maybe the naming is a little unfortunate: Javascript's `const` has more in common with Java's `final` than C's `const`.




Consider applying for YC's Spring batch! Applications are open till Feb 11.

Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: