String concatenation in JavaScript
We use the operator + to concatenate
strings, as well as to add numbers:
javascriptlet str = 'abc' + 'def'; // add two strings
alert(str); // shows 'abcdef'
Strings can also be stored in variables:
javascriptlet str1 = 'abc';
let str2 = 'def';
alert(str1 + str2); // shows 'abcdef'
You can also add variables with strings:
javascriptlet str1 = 'abc';
let str2 = 'def';
alert(str1 + '!!!' + str2); // shows 'abc!!!def'
Let two strings are stored in variables, and we want to insert a space between them when we add them. It's done like this:
javascriptlet str1 = 'abc';
let str2 = 'def';
alert(str1 + ' ' + str2); // shows 'abc def'
Let there be only one variable:
javascriptlet str = 'abc';
alert(str + ' ' + 'def'); // shows 'abc def'
In this case, it makes no sense to arrange the space in the separate string - we will insert it as part of the second term:
javascriptlet str = 'abc';
alert(str + ' def'); // shows 'abc def'
Create the variable str and assign
the string '!!!' to it. Display the
value of this variable on the screen.
Create the variable with the text 'java'
and variable with the text 'script'.
Using these variables and the string concatenation
operation, display the string 'javascript'
on the screen.
Create the variable with the text 'hello'
and variable with the text 'world'.
Display the string 'hello world', using
these variables and the string concatenation operation.