Monday, May 20, 2024
 Popular · Latest · Hot · Upcoming
89
rated 0 times [  96] [ 7]  / answers: 1 / hits: 32459  / 11 Years ago, sat, april 20, 2013, 12:00:00

I am trying to understand what a Javascript immutable variable means. If I can do:



var x = astring;
x = str;
console.log(x); //logs str` , then why it is immutable?


The only answer I can think (from the little bit of C I know) is that var x is a pointer to a memory block with the value astring, and after the 2nd statement it points to another block with the value str. Is that the case?



And a bonus question: I was confused by the value types of Javascript. Are all variables objects under the hood? Even number and strings?


More From » javascript

 Answers
1

Values are immutable; variables are not; they hold a reference to their (primitive) values.



The three primitive types string, number and boolean have corresponding types whose instances are objects: String, Number, Boolean.

They are sometimes called wrapper types.



The following values are primitive:




  • Strings: hello

  • Numbers: 6, 3.14 (all numbers in JavaScript are floating point)

  • Booleans: true, false

  • null: usually explicitly assigned

  • undefined: usually the default (automatically assigned) value



All other values are objects, including wrappers for primitives.



So:




  • Objects are mutable by default

  • Objects have unique identities and are compared by reference

  • Variables hold references to objects

  • Primitives are immutable

  • Primitives are compared by value, they don’t have individual identities



You might find The Secret Life of JavaScript Primitives a good explanation.



Also, in ES6 there is a new const keyword, that creates a read-only named constant that cannot change value through assignment or be re-declared while the script is running.



Hope this helps!


[#78764] Thursday, April 18, 2013, 11 Years  [reply] [flag answer]
Only authorized users can answer the question. Please sign in first, or register a free account.
madelyn

Total Points: 449
Total Questions: 100
Total Answers: 100

Location: Seychelles
Member since Fri, May 7, 2021
3 Years ago
madelyn questions
Wed, Jul 28, 21, 00:00, 3 Years ago
Wed, Jul 14, 21, 00:00, 3 Years ago
Sat, Nov 7, 20, 00:00, 4 Years ago
Thu, Sep 3, 20, 00:00, 4 Years ago
;