3

What is the best way to convert a number to string in javascript? I am familiar with these four possibilities:

Example 1:

let number = 2;
let string1 = String(number);

Example 2

let number = 2;
let string2 = number.toString();

Example 3

let number = 2;
let string3 = "" + number;

Example 4

let number = 2;
let string4 = number + "";

All examples giving the same result, but what is the best option to choose based on Performance? Or is it personal preference?

Thanks for answering.

3
  • 5
    "Best" regarding what? Readability? Performance? Commented Dec 14, 2017 at 10:41
  • 2
    Another one: let number = 2; let string = `${number}` Commented Dec 14, 2017 at 10:42
  • 2
    It makes no sense whatsoever to ask which option would be “the best”, if you do not specify any criteria for what that classification should be based on. Commented Dec 14, 2017 at 10:43

1 Answer 1

4

The problem with approach #2 is that it doesn’t work if the value is null or undefined.

1st , 3rd and 4th which are basically equivalent. ""+value: The plus operator is fine for converting a value when it is surrounded by non-empty strings. As a way for converting a value to string, I find it less descriptive of one’s intentions. But that is a matter of taste, some people prefer this approach to String(value). String(value): This approach is nicely explicit: Apply the function String() to value. The only problem is that this function call will confuse some people, especially those coming from Java, because String is also a constructor.

Sign up to request clarification or add additional context in comments.

5 Comments

If it's null or undefined, then it's not a number in the first place, is it?
yes now you have hardcoaded , what if you are receiving it dynamicaly or getting from some other source.
Then I would hope that you perform if( typeof input !== "number") throw new TypeError("input is not a number!");
sure we can, but if we consider only this question, so i suggest the answers :)
If you receive it from other source you can simply var num=Number(input); to ensure you are dealing with a number, then format it back with num.toString();

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.