Variables and data types
Store values in JavaScript variables with let and const, name them clearly, and work with strings, numbers, booleans, undefined and null, using typeof and template literals.
🎯 By the end of this lesson you will be able to:
- Create variables with const and let, and know when to use each
- Recognise strings, numbers, booleans, undefined and null
- Build text from variables with template literals
Outline
What you'll learn and why it matters
Programs need to remember things: a user's name, the number of items in a basket, whether someone is logged in. A variable is a named place to keep a value so you can use it, and change it, later. Every program you will ever write uses variables.
const and let
const cafeName = "Green Leaf Café";
let cupsSold = 12;
console.log(cafeName);
console.log(cupsSold);
cupsSold = 13;
console.log(cupsSold);Console (Chrome and Edge)
Green Leaf Café 12 13
| Keyword | Can you give it a new value? | Use it for |
|---|---|---|
const | No | Most values: anything that does not need to change |
let | Yes, with = | Counters, totals and values that change |
var | Yes | Old code only. You will see it in tutorials from before 2015; do not use it in new code |
A good habit: start with const. Switch to let only when you find you need to change the value. Trying to change a const stops the script:
const price = 40;
price = 45;The console shows this error
Uncaught TypeError: Assignment to constant variable.
Naming variables
JavaScript names are usually written in camelCase: the first word in lower case and each new word starting with a capital, like cupsSold or totalPrice.
| Name | OK? | Why |
|---|---|---|
totalPrice | Yes | Clear camelCase |
userAge2 | Yes | Numbers are fine after the first character |
2ndPlace | No | Cannot start with a number |
total price | No | No spaces allowed |
let | No | A reserved word that JavaScript already uses |
x | Allowed, but unclear | Choose names that say what the value means |
Types of data
Every value has a type. The typeof operator tells you which:
console.log(typeof "Asha");
console.log(typeof 42);
console.log(typeof 3.5);
console.log(typeof true);
console.log(typeof undefined);Console (Chrome and Edge)
string number number boolean undefined
| Type | Examples | Used for |
|---|---|---|
| string | "Hello", 'chai', ` Hi ` | Text, in double quotes, single quotes or backticks |
| number | 42, 3.5, -10 | Whole numbers and decimals: JavaScript has one number type for both |
| boolean | true, false | Yes/no answers, such as isLoggedIn |
| undefined | undefined | A variable that has not been given a value yet |
| null | null | Deliberately *nothing*, such as *no item selected* |
let nickname;
console.log(nickname);
let selectedItem = null;
console.log(selectedItem);Console (Chrome and Edge)
undefined null
Building text with template literals
Strings written with backticks ` ` are **template literals**. Inside them, ${...}` inserts a value. It is the clearest way to mix text and variables:
const name = "Ravi";
const cups = 3;
const pricePerCup = 40;
console.log(`${name} bought ${cups} cups of chai.`);
console.log(`Total: ₹${cups * pricePerCup}`);Console (Chrome and Edge)
Ravi bought 3 cups of chai. Total: ₹120
You can put any calculation inside ${...}. The older way is to join pieces with +: name + " bought " + cups + " cups". It works, but it is easy to forget the spaces.
You can also give console.log several values separated by commas; it prints them with a space between:
const city = "Pune";
console.log("City:", city);Console (Chrome and Edge)
City: Pune
Practice
Guided exercise
A profile in variables
Store your name, age and whether you are a student in three const variables. Print a sentence using a template literal, then print the type of each variable.
- Create
const name,const age(a number, no quotes) andconst isStudent(trueorfalse). - Print a template literal that uses all three.
- Print
typeoffor each variable.
Show the solution
const name = "Meera";
const age = 19;
const isStudent = true;
console.log(`${name} is ${age}. Student: ${isStudent}`);
console.log(typeof name);
console.log(typeof age);
console.log(typeof isStudent);Console (Chrome and Edge)
Meera is 19. Student: true string number boolean
How to get there: The age has no quotes, so it is a number, not a string. Inside a template literal, ${...} turns each value into text.
Your turn
Count the visitors
Create a let variable visitors set to 0. Add 5, then add 3 more (writing visitors = visitors + 5 and so on), printing the value after each change.
Show the solution
let visitors = 0;
visitors = visitors + 5;
console.log(`Visitors: ${visitors}`);
visitors = visitors + 3;
console.log(`Visitors: ${visitors}`);Console (Chrome and Edge)
Visitors: 5 Visitors: 8
How to get there: The value changes, so visitors must be declared with let. visitors = visitors + 5 reads the old value, adds 5 and stores the result back. In lesson 3 you will see the shortcut visitors += 5.
Common mistakes
Changing a const
You see: TypeError: Assignment to constant variable.
Fix: Use let for values that change.
Declaring the same name twice with let or const
You see: SyntaxError: Identifier 'total' has already been declared
Fix: Declare once; afterwards just assign: total = 10;.
Using normal quotes for a template literal
You see: The console prints ${name} literally
Fix: Template literals need backticks ` ``, usually the key left of 1.
Putting a number in quotes
You see: "5" is text, so maths behaves strangely (lesson 3)
Fix: Write numbers without quotes.
Using a variable before creating it
You see: ReferenceError: Cannot access 'total' before initialization
Fix: Declare variables above the lines that use them.
Recap
constfor values that stay the same,letfor values that change; avoidvar.- Name variables in camelCase with clear meanings; names are case-sensitive.
- Main types: string, number, boolean, undefined and null;
typeofshows the type. - Template literals use backticks and
${...}to insert values into text.
Key terms
- Variable
- A named place in a program that holds a value.
- camelCase
- Writing names with the first word lower case and later words capitalised, like totalPrice.
- Template literal
- A string in backticks that can include values with ${...}.
Check your understanding
Answer all 4 questions, then check your answers to see an explanation for each one.
1. Which keyword should you use for a score that goes up during a game?
2. What does `console.log(typeof "42")` print?
3. What does this print? const item = "tea"; console.log(`One ${item}, please`);
4. Which is a valid variable name?
Mark this lesson complete
Finished this lesson?
When you have worked through the examples and exercises, mark it complete to save your progress.