In this lesson we learn about JavaScript Variables and start coding with them.
Variables are containers for storing data values and objects. For example in a game you might have a 'score' variable. At the start of the game the 'score' variable would be 0 and then each time your get a point in the game it would be added onto the 'score' variable.
Using programming blocks, the code would look like this:
Description | Code |
---|---|
Create and set up the score variable. |
let score = 0 |
Add 1 to the score. |
input.onButtonPressed(Button.A, function () { score += 1 }) |
Show the score. |
basic.forever(function () { basic.showNumber(score) }) |
Using JavaScript, the code would look like this:
Description | Code |
---|---|
Create and set up the score variable. |
|
Add 1 to the score. |
|
Show the score. |
|
In this example apples
, oranges
and fruit
, are variables.
let apples = 4
let oranges = 6
let fruit = apples + oranges
In programming, just like in algebra, we use variables (like apples
) to hold values.
In programming, just like in algebra, we use variables in expressions (fruit
= apples
+ oranges
).
What value will fruit
be equal to?
In JavaScript we can also "add" or join strings together, this is called concatenating them.
let firstName = "LeBron"
let lastName = "Smith"
let fullName = firstName + " " + lastName // join or concatenate them with a space in the middle
In this example the fullName
variable will be equal to LeBron Smith.
All JavaScript variables must be identified with unique names. These unique names are called identifiers. Identifiers can be short names (like x and y) or more descriptive names (age, firstName, country).
The general rules for constructing names for variables (unique identifiers) are:
The following are examples of variables named correctly:
let x = 10
let X = 20
let _age = 15
let dateOfBirth = "8/5/2005"
let country_name = "Mexico"
let $height = "5 foot 7 inches"
The following are examples of variables named incorrectly.
let city = "London"
let city = "Dublin" // can't use the same name
let age% = 15 // can't use symbols
let date Of Birth = "8/5/2005" // can't have spaces
Now that we've learnt about JavaScript variables, let's create and use some in JavaScript code.
Go to the https://makecode.microbit.org website, create a new project and switch to JavaScript instead of Blocks.
Create the following 3 variables and store your own name and age in them.
firstName
lastName
age
Go to the Makecode.com Microbit website using the link below and click on the 'New Project' button underneath the 'My Projects' heading.
Install the micro:bit app on your iPad or tablet.
Open the app, tap 'Create code' and then create a new project.