JavaScript Basics: Your First Programs
Variables and Data Types
In this lesson you will
- Declare variables with let and const
- Recognise the basic data types
- Build text with template literals
Introduction
Programs need to remember things: a player's score, a name, whether someone is logged in. A variable is how a program remembers.
The simple explanation
A variable is a labelled box that holds a value.
You give the box a name, put a value inside, and use the name whenever you need the value again.
letcreates a variable.ageis its name.=means store the value on the right into the name on the left. It is not "equals" like in maths.
Quick quiz
What does the = sign do in let score = 10; ?
let and const
letis for values that will change.constis for values that will not be reassigned. Prefer it by default.
The last line throws an error: you cannot reassign a const. You may also see var in old code. Avoid it in new code.
Naming variables
- Start with a letter,
_or$. Never start with a number. - Names are case-sensitive:
scoreandScoreare different. - The usual style is camelCase:
firstName,totalPrice. - Choose meaningful names:
priceis better thanp.
Data types
Values come in different types. The basic ones:
- String: text, in quotes:
"hello"or'hello'. - Number: whole or decimal numbers:
42,3.14. - Boolean:
trueorfalse. - undefined: a variable that has no value yet.
- null: an intentional "nothing".
typeof tells you the type of a value.
The last line prints object. That is a famous historical quirk of JavaScript. null is not really an object.
Template literals
Backticks let you put variables inside text using ${ }.
Quick quiz
Which keyword declares a variable that should not be reassigned?
Try it yourself
Make variables for your name, your favourite number and whether you like pizza (a boolean). Print one sentence using all three with a template literal.
Summary
- Variables store values:
letfor changing values,constfor fixed ones. - Basic types: string, number, boolean, undefined and null.
typeofshows a value's type.- Template literals mix variables into text:
${ }.
Lesson complete
+20 XP
Nice work. Keep going while it is fresh.
Sources and further reading