Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is number in JavaScript immutable? [duplicate]

Tags:

javascript

Possible Duplicate:
javascript numbers- immutable

I read Douglas Crockford's book JavaScript: the Good Parts. It says the number in JavaScript is immutable. But numbers in JavaScript is copied by value and we can use operator ++ to change the value. So why say it's immutable? and further, if it's immutable, why numbers are copied by value?

like image 283
Xiaotian Pei Avatar asked May 18 '12 07:05

Xiaotian Pei


People also ask

Which value is immutable in JavaScript?

In JavaScript String and Numbers are immutable data types. JavaScript is not a good language to work with data in an immutable fashion. In JavaScript Arrays and Objects are not immutable. Their values can be changed over time.

Are strings in JavaScript immutable?

String specifications among programming languages vary, however most languages treat them as reference types. But strings in JavaScript are different. They are immutable primitives. This means that the characters within them may not be changed and that any operations on strings actually create new strings.

Are arrays immutable js?

Arrays and Objects Are Mutable Arrays and objects are not immutable in JavaScript because they can indeed change their value over time.


1 Answers

They are immutable because they are copied by value.

When you do

var x = 4;
x += 1;

you haven't changed the number 4 into the number 5. You have changed the value stored in the variable x from 4 to 5.

like image 170
Greg B Avatar answered Oct 08 '22 02:10

Greg B