1
<script>
var num = new Number(43);
console.log(num);
</script>

According to the tutorial here: http://www.w3schools.com/jsref/jsref_obj_number.asp

Syntax
var num = new Number(value);
Note: If the value parameter cannot be converted into a number, it returns NaN (Not-a-Number).

Question:

In firebug->console, it shows: Number {} , not what I expect Number {43}, no matter what number i put in new Number(value); it always shows:Number {} so what is the purpose to use new Number(value)? how does it work? BTW, I googled on line, but did not find a good explanation.

user2294256
  • 1,029
  • 1
  • 13
  • 22

2 Answers2

1

Number(43) is a number primitive but new Number(43) will create an object from that number primitive. The display Number {} is just how the Chrome console displays an object like that.

new Number(43) will still "behave" like a number. In the console:

var num = new Number(43); // Number {}
num == 43 // true
num + 5 // 48
num === 43 // false, since the types don't match.

For more info on how new works: How does the new operator work in JavaScript?. If you just want a number primitive, don't use new.

Community
  • 1
  • 1
tb11
  • 3,056
  • 21
  • 29
0

There's a difference between a number primitive and a number object. When you use the new keyword, you create a new number object, which is what you see. You can get the value of the number object with valueOf, which returns the primitive:

> var n = new Number(42);
> n.valueOf()
42
Blender
  • 289,723
  • 53
  • 439
  • 496