0

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
  • 1
    The primitive is converted temporarily into an object to call the method, then the object is gone
    – Esailija
    Commented Nov 11, 2012 at 12:40

2 Answers 2

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.

1

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
  • i know that both of them give the same result but when and why should i prefer one method over the other? Commented Nov 11, 2012 at 12:15
  • @user1463541: 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 new <Type>() notation. Commented Nov 11, 2012 at 13:37

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.