Javascript const to string

The `toString()` Function in JavaScript

Most JavaScript objects and primitive values have a toString() function that converts the value to a string. Many built-in methods use toString() under the hood, like the browser’s alert() function.

Primitives

JavaScript number primitives have a toString() function that converts the number to a string. This is one of the most common uses for toString() :

const num = 42; num.toString(); // '42' typeof num.toString(); // 'string' // Can also use `toString()` on a number literal as long as you // use parentheses. (42).toString(); // '42'

All primitive values except null and undefined have a toString() function: strings, numbers, booleans, BigInts, and symbols.

// String: 'Hello'.toString(); // 'Hello' // Number: (42).toString(); // '42' // Boolean: true.toString(); // 'true' // BigInt: 42n.toString(); // '42' // Symbol: Symbol('test').toString(); // 'Symbol(test)'

The important takeaway is that it is safe to call toString() on an arbitrary JavaScript value as long as that value is not null or undefined . The easiest way to check is to use == null : the most common use for == is that v == null is shorthand for v === null || v === undefined .

if (v != null) < // Won't throw an error, unless you wrote a custom `toString()` that throws v.toString(); >

Objects

The Object class in JavaScript is the base class for all objects, and it has a simple toString() method that usually prints [object Object] :

// Equivalent to `const obj = <>;` const obj = new Object(); obj.toString(); // '[object Object]'

The [object Object] output is often confusing to beginners because they want to see the object’s keys and values. You can loop over the object’s keys and values yourself, but the easiest one-liner is to use JSON.stringify() .

const obj = < name: 'Jean-Luc Picard', rank: 'Captain' >; // '' console.log(JSON.stringify(obj));

If you define a JavaScript class, you can overwrite the toString() function to return whatever you want:

class MyClass < toString() < return 'Hello, World!'; > > const obj = new MyClass(); obj.toString(); // 'Hello, World!'

toString() Parameters

Some toString() functions take parameters, most notably numbers and Node.js buffers.

Читайте также:  Dash html div children

The toString() function for JavaScript numbers takes a radix parameter that defines the base of the numeral system. In other words, num.toString(2) converts the number to a binary number string, num.toString(10) converts the number to a base-10 string, and num.toString(16) converts the number to a hexadecimal string.

(3).toString(2); // '11' (42).toString(10); // '42' (29).toString(16); // '1d'

The Node.js buffer toString() function takes an encoding parameter that is usually one of ‘utf8’, ‘hex’, or ‘base64’. This determines how the raw data in the buffer is encoded.

const fs = require('fs'); const buf = fs.readFileSync('./package.json'); buf.toString('utf8'); // '< "name": "masteringjs.io", . >'

More Fundamentals Tutorials

Источник

# 5 Ways to Convert a Value to String in JavaScript

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 + ''; // '1,2,3' object + ''; // '[object Object]' undefinedValue + ''; // 'undefined' nullValue + ''; // 'null' // ⚠️ symbolValue + ''; // ❌ TypeError 

From here, you can see that this method will throw an TypeError if the value is a Symbol . Otherwise, everything looks pretty good.

# Template String

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

The result of using Template String is essentially the same as Concat Empty String. Again, this might not be the ideal way when dealing with Symbol as it will throw a TypeError .

This is the TypeError if you’re curious: TypeError: Cannot convert a Symbol value to a string

# JSON.stringify()

// ⚠️ JSON.stringify(string); // '"hello"' JSON.stringify(number); // '123' JSON.stringify(boolean); // 'true' JSON.stringify(array); // '[1,"2",3]' JSON.stringify(object); // '' JSON.stringify(nullValue); // 'null' JSON.stringify(symbolValue); // undefined JSON.stringify(undefinedValue); // undefined 

So you typically would NOT use JSON.stringify to convert a value to a string. And there’s really no coercion happening here. I mainly included this way to be complete. So you are aware of all the tools available to you. And then you can decide what tool to use and not to use depending on the situation 👍

One thing I want to point out because you might not catch it. When you use it on an actual string value, it will change it to a string with quotes.

You can read more about this in Kyle Simpson, «You Don’t Know JS series»: JSON Stringification

Side note on the importance of knowing your fundamentals!

Yes, you may have noticed in my code notes, I frequently quote Kyle’s books. I honestly have learned a lot of it. Not coming from a computer science background, there is a lot of fundamentals concept I’m lacking. And his book has made me realize the importance of understanding the fundamentals. For those, who want to be a serious programmer, the way to level up is really TRULY understand the fundamentals. Without it, it’s very hard to level up. You end up guessing the problem. But if you know the fundamentals, you will understand the «why» of something. And knowing the «why» will help you better execute the «how». Anyhoo, highly recommend this series for those trying to becoming a senior 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(); // ❌ TypeError 

So the battle really comes down to toString() and String() when you want to convert a value to a string. This one does a pretty good job. Except it will throw an error for undefined and null . So definitely be mindful of this

# 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' 

Alright, I think we found the winner 🏆

As you can see, the String() method handles the null and undefined quite well. No errors are thrown — unless that’s what you want. Remember my suggestion is generally speaking. You will know your app the best, so you should pick the most suitable way for your situation.

# Conclusion: String() 🏆

After showing you how all the different methods handle different type of value. Hopefully, you are aware of the differences and you will know what tool to pick up the next time you tackle your code. If you’re not sure, String() is always a good default 👍

# Why you shouldn’t use new String()

You might notice in Airbnb’s styleguide, it mentioned to not use new String() . Let’s see why:

const number = 123; typeof new String(number); // 'object' 

So when you create a value using a constructor with the new keyword, you’re actually creating an object wrapper. And this is what it outputs:

console.log(new String(number)); // String 

The point is, new String(«123») creates a string wrapper object around «123», not just the primitive «123» value itself. [edited]

One reason why you’d do this is:

There’s very little practical use for String objects as created by new String(«foo»). The only advantage a String object has over a primitive string value is that as an object it can store properties:

var str = "foo"; str.prop = "bar"; alert(str.prop); // undefined var str = new String("foo"); str.prop = "bar"; alert(str.prop); // "bar" 

# Community Input

: I would use a different method depending on the application:

  • «» + val: simply cast number to string — let’s say inside of the .map()
  • JSON.stringify(val): need to convert small non-nested object
  • .toString(radix): convert number to hexidecimal or binary

: Carefully when using JSON.stringify, that will change a string into a string with quotes 😉

: I also know: new String (foo) but I don’t like this method (it will create an object of String, in contrast to String (without «new») which create string primitive)

: when concat empty string, it’s mostly correct to declare the empty strings first, because when you concat more one values, the sum has been processed first.

1 + 2 + 3 + ''; // 6 '' + 1 + 2 + 3; // 123 

Источник

The `toString()` Function in JavaScript

Most JavaScript objects and primitive values have a toString() function that converts the value to a string. Many built-in methods use toString() under the hood, like the browser’s alert() function.

Primitives

JavaScript number primitives have a toString() function that converts the number to a string. This is one of the most common uses for toString() :

const num = 42; num.toString(); // '42' typeof num.toString(); // 'string' // Can also use `toString()` on a number literal as long as you // use parentheses. (42).toString(); // '42'

All primitive values except null and undefined have a toString() function: strings, numbers, booleans, BigInts, and symbols.

// String: 'Hello'.toString(); // 'Hello' // Number: (42).toString(); // '42' // Boolean: true.toString(); // 'true' // BigInt: 42n.toString(); // '42' // Symbol: Symbol('test').toString(); // 'Symbol(test)'

The important takeaway is that it is safe to call toString() on an arbitrary JavaScript value as long as that value is not null or undefined . The easiest way to check is to use == null : the most common use for == is that v == null is shorthand for v === null || v === undefined .

if (v != null) < // Won't throw an error, unless you wrote a custom `toString()` that throws v.toString(); >

Objects

The Object class in JavaScript is the base class for all objects, and it has a simple toString() method that usually prints [object Object] :

// Equivalent to `const obj = <>;` const obj = new Object(); obj.toString(); // '[object Object]'

The [object Object] output is often confusing to beginners because they want to see the object’s keys and values. You can loop over the object’s keys and values yourself, but the easiest one-liner is to use JSON.stringify() .

const obj = < name: 'Jean-Luc Picard', rank: 'Captain' >; // '' console.log(JSON.stringify(obj));

If you define a JavaScript class, you can overwrite the toString() function to return whatever you want:

class MyClass < toString() < return 'Hello, World!'; > > const obj = new MyClass(); obj.toString(); // 'Hello, World!'

toString() Parameters

Some toString() functions take parameters, most notably numbers and Node.js buffers.

The toString() function for JavaScript numbers takes a radix parameter that defines the base of the numeral system. In other words, num.toString(2) converts the number to a binary number string, num.toString(10) converts the number to a base-10 string, and num.toString(16) converts the number to a hexadecimal string.

(3).toString(2); // '11' (42).toString(10); // '42' (29).toString(16); // '1d'

The Node.js buffer toString() function takes an encoding parameter that is usually one of ‘utf8’, ‘hex’, or ‘base64’. This determines how the raw data in the buffer is encoded.

const fs = require('fs'); const buf = fs.readFileSync('./package.json'); buf.toString('utf8'); // '< "name": "masteringjs.io", . >'

More Fundamentals Tutorials

Источник

Оцените статью