Nishaglobal Education logo

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.

Lesson 2 of 1330 minQuiz: 4 questions

🎯 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
  1. What you'll learn and why it matters
  2. const and let
  3. Naming variables
  4. Types of data
  5. Building text with template literals
  6. Practice
  7. Common mistakes
  8. Recap
  9. Quiz
  10. Mark lesson complete

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

JavaScript
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
KeywordCan you give it a new value?Use it for
constNoMost values: anything that does not need to change
letYes, with =Counters, totals and values that change
varYesOld 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:

JavaScript
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.

NameOK?Why
totalPriceYesClear camelCase
userAge2YesNumbers are fine after the first character
2ndPlaceNoCannot start with a number
total priceNoNo spaces allowed
letNoA reserved word that JavaScript already uses
xAllowed, but unclearChoose names that say what the value means

Types of data

Every value has a type. The typeof operator tells you which:

JavaScript
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
TypeExamplesUsed for
string"Hello", 'chai', ` Hi `Text, in double quotes, single quotes or backticks
number42, 3.5, -10Whole numbers and decimals: JavaScript has one number type for both
booleantrue, falseYes/no answers, such as isLoggedIn
undefinedundefinedA variable that has not been given a value yet
nullnullDeliberately *nothing*, such as *no item selected*
JavaScript
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:

JavaScript
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:

JavaScript
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.

  1. Create const name, const age (a number, no quotes) and const isStudent (true or false).
  2. Print a template literal that uses all three.
  3. Print typeof for each variable.
Show the solution
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
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

  • const for values that stay the same, let for values that change; avoid var.
  • Name variables in camelCase with clear meanings; names are case-sensitive.
  • Main types: string, number, boolean, undefined and null; typeof shows 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. 1. Which keyword should you use for a score that goes up during a game?

  2. 2. What does `console.log(typeof "42")` print?

  3. 3. What does this print? const item = "tea"; console.log(`One ${item}, please`);

  4. 4. Which is a valid variable name?

Answer all 4 questions to check.

Mark this lesson complete

Finished this lesson?

When you have worked through the examples and exercises, mark it complete to save your progress.