Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Understanding JavaScript Object(value)

Tags:

javascript

I understand that the following code wraps a number into an object:

var x = Object(5);

I therefore expect and understand the following:

alert(x == 5); //true
alert(x === 5); //false

However, I also understand that an object is a list of key/value pairs. So I would have expected the following to be different:

alert(JSON.stringify(5)); //5
alert(JSON.stringify(x)); //5

What does the structure of x look like? And why does it not appear to be in key/value pair format?

like image 715
Sandy Avatar asked Jan 03 '16 20:01

Sandy


People also ask

What is JavaScript object value?

Object. values() returns an array whose elements are the enumerable property values found on the object. The ordering of the properties is the same as that given by looping over the property values of the object manually.

What do you understand by JavaScript object?

In JavaScript, an object is a standalone entity, with properties and type. Compare it with a cup, for example. A cup is an object, with properties. A cup has a color, a design, weight, a material it is made of, etc. The same way, JavaScript objects can have properties, which define their characteristics.


1 Answers

The Object constructor creates an object wrapper for the given value, of a Type that corresponds to the value.

So you get a Number object with the primitive value 5 when passing a number to Object

var x = Object(5);

it's exactly the same as doing

var x = new Number(5);

when calling valueOf() on both, you get the primitive value 5 back again, which is why stringifying it gives the same as stringifying the number 5, the object is converted to it's primitive value before stringifying

The specification for JSON.stringify says

Boolean, Number, and String objects are converted to the corresponding primitive values during stringification, in accord with the traditional conversion semantics.

like image 186
adeneo Avatar answered Oct 02 '22 08:10

adeneo