#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    30
    Rep Power
    5

    Question Primitive values immutable or not?


    Hello

    I'm reading David Flanagan's "JavaScript: The Definitive Guide 6th ed", which says on page 44:
    There is a fundamental difference in JavaScript between primitive values (undefined, null, booleans, numbers, and strings) and objects (including arrays and functions). Primitives are immutable: there is no way to change (or “mutate”) a primitive value.
    And still, the following code works:
    Code:
    "use strict";
    
    var myvar = "hello, world!";
    myvar = "changed!";
    
    function myfunc(){
    	console.log("Before");
    	//alert(myvar);
    	document.write(myvar);
    	console.log("After");
    }
    I expected to get an error with "myvar="changed!";" but it works. Did I misunderstand what is meant with primitives being immutable?

    Thank you.
  2. #2
  3. JavaScript is not spelt java
    Devshed Novice (500 - 999 posts)

    Join Date
    Feb 2011
    Location
    Landan, England
    Posts
    743
    Rep Power
    165
    Code:
    var myvar = "hello, world!";
    myvar = "changed!";
    I know it seems that you are changing myvar but, technically, you are not. The 2nd line creates a new string that myvar now points to. The previous string "hello, world!" still exists (unaltered) in the computers' memory - but it's of no use as nothing points to it. (It will be removed from memory later by a process called garbage collection.)

    Similarly,

    Code:
    var myvar = "Hello World!";
    myvar = myvar + " Yo!";
    does not modify myvar; the 2nd line (again) creates a new string. This is why string operations can be expensive.

    Comments on this post

    • Kravvitz agrees
    "The mysql extension is deprecated as of PHP 5.5.0, and is not recommended for writing new code as it will be removed in the future. Instead, either the mysqli or PDO_MySQL extension should be used." the docs
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    May 2010
    Posts
    30
    Rep Power
    5
    Thanks for the info.

    So primitive values cannot be changed in the sense that a new variable will be created on the fly, not in the sense that it would trigger an error as I expected.

IMN logo majestic logo threadwatch logo seochat tools logo