Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Checking if data is immutable

Tags:

javascript

What is the quickest and cleanest way to test if a var holds immutable data (i.e. is string, number, boolean, null, undefined)?

E.g. When var test is mutable, the following is legal:

var test = {}; 
//the next 2 lines work because `test` has mutable data
test.someFun = function () { alert(this); };
test.someFun(); 

but when var test is immutable, it's illegal:

var test = "string"; 
//the next 2 lines are invalid, as `test` is a primitive
test.someFun = function () { alert(this); };
test.someFun(); 
like image 930
jball Avatar asked Dec 09 '10 19:12

jball


People also ask

How do you know if its mutable or immutable?

An object is mutable if it is not immutable. An object is immutable if it consists, recursively, of only immutable-typed sub-objects. Thus, a tuple of lists is mutable; you cannot replace the elements of the tuple, but you can modify them through the list interface, changing the overall data. Save this answer.

How do you check if something is immutable in Python?

Since immutability completely depends on the implementation of the methods, no there is no way to know whether an object is immutable.

What data is immutable?

Immutable data is a piece of information in a database that cannot be (or shouldn't be) deleted or modified.

Which data type is not immutable?

So all data types, except objects, are Immutable, which means you won't change the original variables value if you change the value of the one its assigned to.


1 Answers

Just another short option:

function isPrimitive(value) {
  return Object(value) !== value;
}

How does it works:

If the value is a primitive value that is convertible to object, such as a Number, String or a Boolean, the strict equality operator will return true, since the Object constructor called as a function, will convert the value to a "wrapped object":

typeof 5;         // "number"
typeof Object(5); // "object", a wrapped primitive
5 === Object(5);  // false

If the value is a primitive not convertible to Object, such as null or undefined, the Object constructor will create a new empty object, returning true.

The last case, if value holds a reference to an object, the Object constructor will do nothing, and the strict equality operator will return false.

like image 61
Christian C. Salvadó Avatar answered Sep 22 '22 01:09

Christian C. Salvadó