![]() 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. 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. 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.
0 Comments
Leave a Reply. |
Details
AuthorWrite something about yourself. No need to be fancy, just an overview. ArchivesCategories |