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();
asked Nov 10, 2012 at 17:40
1
  • 1
    The primitive is converted temporarily into an object to call the method, then the object is gone 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.

Arseni Mourzenko
138k32 gold badges355 silver badges540 bronze badges
answered Nov 10, 2012 at 22:11
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.

answered Nov 10, 2012 at 22:21
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

Draft saved
Draft discarded

Sign up or log in

Sign up using Google
Sign up using Email and Password

Post as a guest

Required, but never shown

Post as a guest

Required, but never shown

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

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.