Understanding Javascript immutable variable -
i trying understand javascript immutable variable means. if can do:
var x = "astring"; x = "str"; console.log(x); //logs str` , why immutable?
the answer can think (from little bit of c know) var x pointer memory block value "astring", , after 2nd statement points block value "str". case?
and bonus question: confused value types of javascript. variables objects under hood? number , strings?
values immutable; variables not; hold reference (primitive) values.
the 3 primitive types string, number , boolean have corresponding types instances objects: string, number, boolean.
called wrapper types.
the following values primitive:
- strings: "hello"
- numbers: 6, 3.14 (all numbers in javascript floating point)
- booleans: true, false
- null: explicitly assigned
- undefined: default (automatically assigned) value
all other values objects, including wrappers primitives.
so:
- objects mutable default
- objects have unique identities , compared reference
- variables hold references objects
- primitives immutable
- primitives compared value, don’t have individual identities
you might find the secret life of javascript primitives explanation.
also, in es6 there new const keyword, creates read-only named constant cannot change value through assignment or re-declared while script running.
hope helps!
Comments
Post a Comment