Variable with String Concatenation Pattern

Name Code (Block) Code (Text)
String Concatenation with Variables var myString = "rock";
var myOtherString = "roll";

var myStory = myString + " and " + myOtherString;

The model could be read like so:

The variable myString gets the value "rock". The variable myOtherString gets the value "roll". The variable myStory evaluates the expression myString + " and " + myOtherString to "rock and roll". "rock and roll" is now stored in myStory.

How does it work?

Strings are any characters, symbols or numbers that are contained within quotation marks.

"My best friend"
"243"
"Wow!"

Concatenation is used to combine a string with another string or number. Those strings or numbers can even be stored in variables!

To concatenate use the + between values.

"Up" + " and " + "down"

To use the Variable with String Concatenation Pattern a variable is defined which stores the value of a string combined with another string or number.

Examples

The variable myName gets the value "Randy". The variable myAge gets the value 16. The variable statement evaluates the expression myName + " is " + myAge + " years old." to "Randy is 16 years old.". "Randy is 16 years old." is stored in the variable statement which is then printed to the console.



The variable score gets the value 0. The variable lives gets the value 3. The variable stats evaluates the expression "Score: " + score + " Lives: " + lives to "Score: 0 Lives: 3". "Score: 0 Lives: 3" is stored in the variable stats which is then printed to the console.



The variables are updated each time the buttons are clicked using the Counter Pattern with Event. The stats variable gets the values of the score and lives variables and concatenates them with "Score: " and "Lives: " before updating the display on the screen.

Found a bug in the documentation? Let us know at documentation@code.org