Lesson 2: Variables and Types
Variables
We use variables to assign values that we want to use later in our code, usually repeatedly. There are two keywords for variables; const and let. The const variable cannot be re-assigned another value after a value has been declared. This is different to a let variable, which can be changed as many times as needed in the local scope of code.
Note: that in older versions of JavaScript, variables can be created be using the var keyword. It is generally recommended to not use this as var is not limited by its scope. We will learn more about scope in a later lesson.
Types
There are different types of variable data types. Some primitive data types include String, Number, Boolean values and null.
- String - A String is a collection of characters such as letters, number and special symbols inserted in between double or single quotation marks. e.g., "John went to the shop and bought $20 worth of apples!"
- Number- A Number is any numeric value. These are not placed between quotation marks.
- Boolean- A Boolean can have one of only two values: true or false.
- Null- Null represents the absence of a value. An empty value is represented by null if it is printed to the console.
Try It!
Assign values to the following variables name in index.js. Notice how we can change the value of the let variable, but we cannot change the value of the const variable.
Concatenation
Strings and variables can be concatenated together to form a single string by using the + operator as done above.
Example:
let day = "Tuesday";
let weather = "raining";
console.log("Today is "+ day + "and it will be " + weather);
Interpolation
Interpolation is the process of evaluating string literals containing one or more placeholders. Add a variable inside a string use back ticks and the `${ ... }` format.
let day = "Tuesday";
let weather = "raining";
console.log("Today is {day} and it will be {weather}");
Further Reading