The Java programmers know to call toString()method in order to convert any value to string. That is also the case with JavaScript.

Using toString() method

1
2
3
4
5
const balance = 910;

const notification = 'You owe me ' + balance.toString(1);

console.log(notification); // You owe me 910

Tip: toString() also accepts an argument to represent the numeric values with respect to a base. Please refer the docs to make a better use of it.

Since the ES6 standard, we have another way as well, called template string literals.

Using template string literal

1
2
3
4
5
const balance = 910;

const notification = `You owe me ${balance}!`;

console.log(notification); // You owe me 910!

Looks good is it not ^_^

Tip: Prefer template strings whenever constructing strings with values or object references.

Using JSON.stringfy() method

1
2
3
4
5
const balance = 910;

const notification = 'You owe me ' + JSON.stringify(balance);

console.log(notification); // You owe me 910

This really comes handy for objects in order to print the object structure in string notation. JSON.stringfy accepts two more arguments called replacer and space respectively.

Tip: Prefer to supply space argument when stringfying objects. Refer docs for more.

Using String() constructor

1
2
3
4
5
const balance = 910;

const notification = 'You owe me ' + new String(balance);

console.log(notification); // You owe me 910

There is this constructor option for us to be OOPs.

Tip: Use String() without the new keyword to get string literal instead. We can verify the same with typeof operator as well.

1
2
3
4
5
6
7
8
9
10
const stringObject = new String('AshKeys');

console.log(typeof stringObject); // object

const stringLiteral = String('AshKeys');

console.log(typeof stringLiteral); // string

console.log(stringObject == stringLiteral); // true
console.log(stringObject === stringLiteral); // false

As you can see, stringObject is value equals with stringLiteral, but does not strict equals it.