For the first time, I hope you can improve your reading ability

If you subscribe to Airbnb’s JavaScript style guide, you know that the best way to do this is to use “String()” 👍

I use it because it’s the most explicit — it’s easy for others to understand the intent of your code 🤓

Keep in mind that the best code doesn’t need to be clever, but to communicate your understanding of the code to others

const value = 12345;

// Concat Empty String
value + ' ';

// Template Strings
`${value}`;

// JSON.stringify
JSON.stringify(value);

// toString()
value.toString();

// String()
String(value);

// RESULT
// '12345'
Copy the code

Compare these five methods

Let’s test these five methods with different values. Here are the values we intend to test:

const string = "hello";
const number = 123;
const boolean = true;
const array = [1, "2", 3];
const object = {one: 1 };
const symbolValue = Symbol('123');
const undefinedValue = undefined;
const nullValue = null;
Copy the code

Concatenating empty strings

string + ' '; // 'hello'
number + ' '; // '123'
boolean + ' '; // 'true'
array + ' '; // '1, 2, 3'
object + ' '; // '[object Object]'
undefinedValue + ' '; // 'undefined'
nullValue + ' '; // 'null'/ / ⚠ ️ symbolValue +' '; / / ❌ TypeErrorCopy the code

As you can see from this, this method raises a TypeError if the value is symbol, but otherwise prints the correct value

Template string

`${string}`; // 'hello'
`${number}`; // '123'
`${boolean}`; // 'true'
`${array}`; // '1, 2, 3'
`${object}`; // '[object Object]'
`${undefinedValue}`; // 'undefined'
`${nullValue}`; // 'null'/ / ⚠ ️ `${symbolValue}`; / / ❌ TypeErrorCopy the code

Using a template string and concatenating string actually outputs the same result. Again, this is not ideal when working with symbols because it throws a TypeError

TypeError: Cannot convert a Symbol value to a string

Type error: cannot convert value of type Symbol to string

JSON.stringify()

/ / ⚠ ️ JSON. Stringify (string); //'"hello"'
JSON.stringify(number); // '123'
JSON.stringify(boolean); // 'true'
JSON.stringify(array); // '[1, "2", 3]'
JSON.stringify(object); // '{"one":1}'
JSON.stringify(nullValue); // 'null'
JSON.stringify(symbolValue); // undefined
JSON.stringify(undefinedValue); // undefined
Copy the code

You wouldn’t normally use json.stringify to convert a value to a string either, and there’s really no coercion here, so I mainly include this way to give you a complete overview of all the tools available, and then you can choose which method to use depending on the situation 👍

There’s one thing I want to point out because you might not have noticed, but when you convert a value in pure string format it gets wrapped around quotes

Expanded read “You Don’t Know JS” by Kyle Simpson: JSON Stringification

About the importance of understanding the fundamentals

You may have noticed that my code notes often refer to Kyle’s book, I learned a lot on it, I’m not from a computer science background, the lack of a lot of basic concepts, the book made me realize how important it is to understand the basic original, for those who want to become a senior engineer, really understand the basic principle is a good way to improve level, otherwise it is difficult to improve. You eventually know what the problem is, but if you know the fundamentals, you’ll know why and how to fix it. Anyway, this series is highly recommended for anyone who wants to be an advanced programmer!

toString()

string.toString(); // 'hello'
number.toString(); // '123'
boolean.toString(); // 'true'
array.toString(); // '1, 2, 3'
object.toString(); // '[object Object]'
symbolValue.toString(); // 'Symbol(123)'/ / ⚠ ️ undefinedValue. ToString (); / / ❌ TypeError nullValue. ToString (); / / ❌ TypeErrorCopy the code

So the comparison is left to toString and String. ToString also performs well, but it’s important to note that exceptions are thrown under undefined and null.

String()

String(string); // 'hello'
String(number); // '123'
String(boolean); // 'true'
String(array); // '1, 2, 3'
String(object); // '[object Object]'
String(symbolValue); // 'Symbol(123)'
String(undefinedValue); // 'undefined'
String(nullValue); // 'null'
Copy the code

Finally, we found the champion 🏆

As you can see, String() handles undefined and null very well and does not throw any exceptions. Remember what I always say, you know your program best, so you should choose what works best for you.

Conclusion Sting 🏆 ()

Having shown you all the different ways to handle different types of values, hopefully you are aware of these differences and know how to use them the next time you work with code. If you are not sure, String() is the best choice 👍

Community opinion

MaxStalker: I use different methods depending on the scenario:

  • “” + val: Just convert the number to a string — in the Map() method
  • Json.stringify (val): Small non-nested objects need to be converted
  • ToString (radix): Digital conversion to hexadecimal or binary

Frontendr: Be careful when using json. stringify, it will subpackage the string into a quoted string.

@super.pro.dev: I also know about new String(foo), but I don’t like this method (it creates a String object, whereas String() creates a String primitive function)

resources

  • MDN Web Docs: toString
  • Airbnb JavaScript Style Guide
  • 2ality: Converting a value to string in JavaScript
  • Convert Number to String
  • Stack Overflow: Casting to string
  • Addition operator in details
  • YDKJS: Coercion