String Concatenation

String concatenation is "adding" strings or, more precisely, creating strings that would result if the two strings were joined together. We're going to do it with the '+' operator. Note that you can also add numbers in JavaScript with the '+' sign but if either or both of the operands (what you're adding) are strings then the result will be a string, calculated using string concatenation and not arithmetic addition. You can also chain them together, e.g. "a"+"b"+"c" becomes "abc"

Examples:

<button onclick="alert('Joe' + ' Blow')">'Joe' + ' Blow'</button> <!--note the space-->

<script type="text/javascript">
var firstName='Joe';
var lastName='Blow';
</script>
<button onclick="alert(firstName+' '+lastName)">firstName + ' ' + lastName</button>
<!--Things to note:
1. I used var inside the onclick to avoid a conflict with the previous example
2. You can have really long Event Handler attribute values and you can put the statements on separate lines. If you do this then use a function instead(once you know what that is).
-->
<button onclick="var firstName=prompt('What is your first name?');
var lastName=prompt('What is your last name?');
alert(firstName+' '+lastName);">firstName + ' ' + lastName with prompts</button>
<button onclick="alert(2 + 2)"> 2 + 2 = ?</button>

<button onclick="alert(2 + '2')">2 + '2' = ?</button>

<button onclick="alert('2' + '2')">'2' + '2' = ?</button>
Back to Knowledge Dump