In JavaScript not every data is an object. There exist a few primitive types, like strings, numbers and Boolean which are not objects. For each of these types there exists a constructor which outputs an object with similar behaviour: Number
, String
and Boolean
. To confuse matters, one actually can call methods on primitive types - they will be converted to the corresponding objects during this operation, and then converted back. For instance one can do
var a = 4.1324;
a.toFixed(1) // Outputs 4.1
Yet, if you try to compare primitive types and objects with strict equality, the difference shows up
var a = new Number(4);
var b = 4;
a === b; // False!!!
typeof a; // 'object'
typeof b; // 'number'
Actually of one tries to compare objects, they turn out to be different anyway:
var a = new Number(4);
var b = new Number(4);
a === b; // False!!!
(From a conceptual point of view I sort of understand the distinction. Objects can have additional properties, hence they should not compare to equal unless they are actually the same. So if we want to have 4 === 4
we need to use a type which is not an object. But this dilemma is faced by any sufficiently dynamic programming language, yet JavaScript is the only one I know where there are two types - one objectful and one not - for numbers or strings.)
What is the advantage of keeping two separate representations for numbers, strings and Booleans? In what context could one need the distinction between primitive types and objects?
Primitive data types are number, string, boolean, NULL, Infinity and symbol. Non-primitive data types is the object. The JavaScript arrays and functions are also objects.
Primitive values are immutable — they cannot be changed after being created. Object references, however, are mutable and can be changed.
Javascript has two types of values: primitive values and reference values. You can add, change, or delete properties to a reference value, whereas you cannot do it with a primitive value. Copying a primitive value from one variable to another creates a separate value copy.
Variables in Java are classified into primitive and reference variables. From the programmer's perspective, a primitive variable's information is stored as the value of that variable, whereas a reference variable holds a reference to information related to that variable.
What is the advantage of keeping two separate representations for numbers, strings and Booleans?
Performance
In what context could one need the distinction between primitive types and objects?
Coercion comes to mind. 0 == false
while new Number(0) != false
So for instance:
var a = new Boolean(false);
if(a) {
// This code runs
}
but
var a = false;
if(a) {
// This code never runs
}
You can read more about coercion here: JavaScript Coercion Demystified
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