DailyJS

JavaScript news and opinion.

Member-only story

5 Ways to Convert a Value to String in JavaScript

--

CodeTidbit by SamanthaMing.com

If you’re following the Airbnb’s Style Guide, the preferred way is using “String()” 👍

It’s also the one I use because it’s the most explicit — making it easy for other people to follow the intention of your code 🤓

Remember the best code is not necessarily the most clever way, it’s the one that best communicates the understanding of your 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'

Comparing the 5 ways

Alright, let’s test the 5 ways with different values. Here are the variables we’re going to test these against:

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;

Concat Empty String

string + ''; // 'hello'
number + ''; // '123'
boolean + ''; // 'true'
array + ''; //

--

--

DailyJS
DailyJS
Samantha Ming
Samantha Ming

Written by Samantha Ming

Frontend Developer sharing weekly JS, HTML, CSS code tidbits🔥 Discover them all on samanthaming.com 💛

Responses (8)