Working with JavaScript Strings: Concatenating a String and Another Data Type 3/12

Working with JavaScript Strings: Concatenating a String and Another Data Type 3/12

Problem

You want to concatenate a string with another data type, such as a number.



Solution

Use the exact same operators, such as addition (+) and shorthand assignment (+=), youuse when concatenating strings:

var numValue = 23.45;
var total = "And the total is " + numValue; // string has "And the total is 23.45"


Discussion

A different process occurs when adding a string and another data type. In the case ofanother data type, such as a Boolean or number, the JavaScript engine first convertsthe other data type’s value into a string, and then performs concatenation:

// add a boolean to a string
var boolValue = true;
var strngValue = "The value is " + boolValue; // results in "The value is true"

// add a number to a string
var numValue = 3.0;
strngValue = "The value is " + numValue; // results in "The value is 3"


The automatic data conversion also applies if you’re concatenating a String object witha string literal, which is a necessary capability if you’re not sure whether the stringsyou’re working with are objects or literals but you still want to create a concatenatedstring:

var strObject = new String("The value is ");
var strngLiteral = "a string";
var strngValue = strObject + strngLiteral; // results in "The value is a string"


The resulting string is a string literal, not a String object.

Comments

Popular posts from this blog

Working with JavaScript Strings: Conditionally Comparing Strings 4/12

Working with JavaScript Strings: Concatenating Two or More Strings 2/12

Working with JavaScript Strings: Finding a Substring in a String 5/12