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 | const balance = 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 | const balance = 910; |
Looks good is it not ^_^
Tip: Prefer template strings whenever constructing strings with values or object references.
Using JSON.stringfy() method
1 | const balance = 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
spaceargument when stringfying objects. Refer docs for more.
Using String() constructor
1 | const balance = 910; |
There is this constructor option for us to be OOPs.
Tip: Use
String()without thenewkeyword to get string literal instead. We can verify the same withtypeofoperator as well.
1 | const stringObject = new String('AshKeys'); |
As you can see, stringObject is value equals with stringLiteral, but does not strict equals it.