Take the 2-minute tour ×
Programmers Stack Exchange is a question and answer site for professional programmers interested in conceptual questions about software development. It's 100% free, no registration required.

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();
share|improve this question
1  
The primitive is converted temporarily into an object to call the method, then the object is gone –  Esailija Nov 11 '12 at 12:40

2 Answers 2

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.

share|improve this answer

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.

share|improve this answer
    
i know that both of them give the same result but when and why should i prefer one method over the other? –  user1463541 Nov 11 '12 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. –  MainMa Nov 11 '12 at 13:37

Your Answer

 
discard

By posting your answer, you agree to the privacy policy and terms of service.

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