
Then, string concatenation is used for the rest of the expression since the first operand is "it is". The addition between a and b is performed first, which leads to the addition operation between the two variables. log ( "it is " + (a + b ) + " motorway" ) // "it is 2468 motorway"

This can be solved using parentheses: const a = 2000 const b = 468 console. So, instead of an addition operation between a and b like the previous example, it becomes a string concatenation operation between the two. log ( "it is " + a + b + " motorway" ) // "it is 2000468 motorway"īecause "it is" + a is evaluated first, the + operator is used for string concatenation for the rest of the expression.
#Js convert int to string code#
However, try changing the code to the following: const a = 2000 const b = 468 console. Once a string variable or literal is reached, the operation becomes a string concatenation. Since a + b is evaluated first before reaching the string, the operation is a numerical addition rather than a string concatenation. log (a + b + " motorway" ) // "2468 motorway" When using this approach with more than one number, an unexpected result might happen.įor example: const a = 2000 const b = 468 console. log ( 10 + "" ) //"10"Ĭonvert Number to String with Concatenation by SitePoint ( CodePen.Īlthough this approach is efficient (as it requires the least amount of code), it can make the code less readable. You can convert a number to a string using the + operator.įor example: console. The second approach is string concatenation.
#Js convert int to string how to#
You might also be interested to how to convert a string to a number if you’re looking to do the opposite action.Ĭonvert a Number to a String Using String Concatenation String and toString() are mostly the same but treat undefined and null variables differently. For example, using numbers as inputs to functions or APIs that expect a string. String or toString(): When changing the type of a number value to a String.You can also use Concatenation but beware. For example, displaying text on a webpage like “You have used 7 credits out of 24”. String Interpolation: When inserting a number value within a string.We recommend different approaches depending on your specific needs and use case: This tutorial explores four ways to convert a number to a string in JavaScript. You might want to do this in order to make number data more readable for users - for example, to display the number as part of a sentence. In this short tutorial, we’ll look at how you can convert a number to a string in JavaScript.

JavaScript is quite flexible and offers many different ways to convert between data types.
