In javascript, what is the difference in applying a toString() method to the primitive datatype, number like this
var myString = myNumber.toString();
and applying the same toString() method by creating a reference datatype equivalent, the Number class like this
var numberObject = new Number(myNumber);
var myString = numberObject.toString();
1
In a chrome console if you type:
new Number(10).toString === (10).toString
It returns true, so I suppose there is no difference between the two since both functions refers to the same reference.
Both are equivalent and give the same result.
JavaScript allows to create objects without using new
keyword.
For example, you may create an array using new Array(1, 2, 3)
, but you may also use the shorter syntax [1, 2, 3]
.
Use shorter notations ((123).toString()
, "hello ".trim()
, [1, 2, 3].reverse()
, etc.) whenever possible. They are explicit enough, so there is no need to pass by a verbose new <Type>()
notation.
2