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.

Yakalent
  • 1,142
  • 2
  • 10
  • 18

1 Answers1

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.

Naveen Kumar
  • 273
  • 2
  • 5
  • 14