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();
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.
Since immutability completely depends on the implementation of the methods, no there is no way to know whether an object is immutable.
Immutable data is a piece of information in a database that cannot be (or shouldn't be) deleted or modified.
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.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With