Learning Goals
At the end of this Tutorial, you will be able to:
- Declare (create and name) variables with the let and const keywords.
- Apply the correct variable naming standards
- Assign string, numeric and boolean data types to variables.
- Assign a null value to a variable.
- Use template literals to mix variables and literals in a string.
- Understand the assignment operator (=) in JavaScript.
- Reveal a variable's type using the typeof operator.
- Recognise JavaScript as a loosely-typed programming language.
Download a new workfile on your computer as described at the link below.
About variables in JavaScript
You can think of a variable as a container or ‘storage box’ for a value that may be different each time the JavaScript code is run.
Consider the example of a website login page that asks for a user's First Name.
The value entered might be 'Laurent' or 'John' or whatever. But in the JavaScript code that stores the value, the variable will always have the same name of, for example, userFirstName.
In JavaScript, the first thing you do with a variable is declare it. The following code declares variables named userFirstName and taxRate. Copy this code into your variables-literals.html workfile.
// Declaring (creating and naming) variables in JavaScript
let userFirstName; // Declares a variable named userFirstName
let taxRate; // Declares a variable named taxRate
Variable declarations begin with the words let or const. These so-called keywords allocate memory storage space for new data and tell JavaScript that a new variable name is in use.
You can see above that two forward slashes // indicate a single-line comment in JavaScript.
const
The JavaScript code is not allowed to change the value first assigned (stored) in this variable.
For example, a person's ID number or date of birth.
let
The JavaScript code is allowed to later reassign (update) the value first stored in the variable.
For example, the score in a computer game. Or a customer's address.
(Older versions of JavaScript used the keyword var to declare a variable. This is no longer recommended.)
Variable names
Here are a few points to remember about variable names:
- Uniqueness: Don't use the same name for two different variables within the same scope of JavaScript code.
- No spaces: Variable names cannot contain spaces. For example:
const Product Name; // Invalid variable name let Sub Total; // Also invalid variable name
- No dashes (-): Variable names cannot contain dashes. For example:
const Product-Name; // Invalid variable name let Sub-Total; // Also invalid variable name
- Case sensitivity: Variable names are case-sensitive. For example:
const firstName; // This is one variable name let FirstName; // This is a DIFFERENT variable name
Using camelCase for variable names
Variable names in JavaScript are typically written in so-called camel case. Multiple words are joined together without spaces (because spaces are not allowed), and each word after the first starts with an uppercase letter. The first word is written in all lowercase.
let postCode; // camel case variable name let localCurrency; // Also camel case variable name let accountBalance; // Also camel case variable name
Assigning values to variables
When you declare a variable, you will often want to assign a value to it. Copy the examples below.
// Declaring variables and then assigning values to them
let userName; // Declare a variable
userName = "Sheila Murphy"; // Assign value to the variable
console.log(userName); // Outputs: Sheila Murphy
let userCountry; // Declare a variable
userCountry = "Ireland"; // Assign value to the variable
console.log(userCountry); // Outputs: Ireland
You can declare a variable and assign a value to it in the same statement on the same line. Here’s two examples.
// Declaring and assigning values to variables on single line
let userEmail = "abcd@email.com";
console.log(userEmail); // Outputs: abcd@email.com
let userPassword = "banana42%";
console.log(userPassword); // Outputs: banana42%
// Do NOT put quotes around a variable name in console.log()
console.log("userPassword"); // Outputs: userPassword
About string variables
The variables you have worked with so far have all been of one type: the string variable. This variable type holds letters, numbers, blank spaces or punctuation symbols.
When you enclose the value in single quotes ('') or double quotes (""), JavaScript assumes that you want to create a string variable. For example:
// Working with string variables
const firstName = "Peter";
let lastName = 'Smith';
let streetAddress = "42 Green Avenue";
console.log(firstName); // Outputs: Peter
console.log(lastName); // Outputs: Smith
console.log(streetAddress); // Outputs: 42 Green Avenue
// Display on one line. Use , character to separate variables
console.log(firstName, lastName, streetAddress);
// Outputs: Peter Smith 42 Green Avenue
When you use the comma , character in a console.log() statement as above, each variable is displayed separately with a space automatically inserted between them.
You will learn more about string variables in the Working with strings Tutorial.
About numeric variables
Another type of variable in JavaScript is the numeric variable, which stores a number with which you can perform arithmetic operations.
When you omit the quotes around the value, JavaScript makes the variable a numeric variable. For example.
// Working with numeric variables
let orderQty = 42;
let productPrice = 9.99;
You never need to tell JavaScript which type of variable you want to work with. JavaScript decides which type of variable you want to declare (create) or re-assign (update) by what type of data you store to it.
- When you enclose the assigned value within quotes or backticks, JavaScript gives the variable a data type of string.
- When you omit the quotes, JavaScript gives the variable a data type of number.
You will learn more about numeric variables in the Working with numbers Tutorial.
About boolean variables
Like other programming languages, JavaScript supports boolean variables. These can have only one of two possible and opposite values:
- The value stored in the boolean variable could be true
- Or the value in the boolean variable could be false.
See some sample booleans below.
No other possible value is allowed.
Boolean variables typically have names that begin with is or similar words that suggest their two allowed values.
Boolean variables are often used to store the results of comparisons or logical operations.
You will learn more about boolean variables in the Making decisions with if and Testing for weird values Tutorials.
About null
values
Sometimes the data you will want to store will be ‘nothing’ or ‘empty’. A null value is JavaScript's way of saying: "This deliberately has no value."
Suppose your task is to record the results of student tests. You create a variable named testScore for this purpose.
Student 1 |
Took the test and achieved a testScore of 85. |
Student 2 |
Took the test and failed every question. The testScore is 0. |
Student 3 |
Did not take the test. Set testScore to null. |
// Setting a null value
let testScore = null; // Assign null without quotes. Not "null" (a string).
About the assignment (=
) operator
Putting a value into a variable is known as assignment, and is achieved through the use of the assignment operator (=). For example:
// About variable assignment
let salePrice = 100;
This places the value of 100 inside the variable named salePrice.
In JavaScript, the = symbol does not mean ‘equal to’ as it does in arithmetic or algebra. It means as follows:
Place in the variable on the left hand side (LHS) whatever is on the right hand side (RHS) of the = sign.
Sometimes, you may want to change a variable's value by a fixed amount. The following would make no sense if it were arithmetic.
// Update variable value
salePrice = salePrice + 25;
console.log(salePrice); // Outputs: 125
But in JavaScript it means ‘increase the salePrice value price by 25.’
Mixing literals with variables
Literals are unchanging items of text, numbers or punctuation characters. Often you will want to include both literals and variables together in the same JavaScript code.
When you enclose the value in single quotes (''), double quotes ("") JavaScript assumes that you want to create a string variable. For example:
Modern JavaScript uses so-called template literals for this purpose.
To write a template literal:
- Enclose everything within a pair of backtick (``) characters.
- Type the literals (regular text) as you normally would, including spaces between words.
- Embed the variables with the ${someVariable} syntax.
Copy the example below into your variables-literals.html workfile.
// Mixing literals and variables
const customerFirstName = "Marie";
const accBalance = 10;
// Using template literals
console.log(`Hi ${customerFirstName}. Your balance is €${accBalance}.`);
// Outputs: Hi Marie. Your balance is €10.
Note that the euro symbol (€) is a string character and not part of the balance numeric variable.
Template literals make it easy to include variables within strings, and to format the output on screen in a way that is easy to read.
The typeof
operator
In this Tutorial, you have been working with four basic data types in JavaScript.
Data Type |
Description |
string |
Text within quotes, such as "Hello, World". |
number |
A number without surrounding quotes, such as 12 or 9.99. |
boolean |
Only two possible values: either true or false. |
null |
A data type that intentionally has no value. |
If you are unsure about a variable’s data type, you can use the typeof operator on the variable as shown below.
// Checking the data type of a variable
let someVar = ""; // declare empty variable
someVar = "12"; // assign string to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: string
someVar = 12; // assign number to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: number
someVar = "12"; // assign string to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: string - again!
someVar = true; // assign boolean to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: boolean
someVar = null; // assign null to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: object (an error in JavaScript)
someVar = 24; // assign number to variable
console.log(`Data type of someVar: ${typeof someVar}`); // Outputs: number - again!
As you can see, the someVar variable goes through many changes of data type.
Note also that the data type of null outputs as ‘object.‘ This is an error in the JavaScript programming language itself.
You can think of the typeof operator as like asking: "What kind of thing is this?"
JavaScript: a loosely-typed language
JavaScript is what’s called a loosely-typed or dynamically-typed language. JavaScript decides the data type of a variable automatically based on the value you enter to it. This means:
- You don't need to specify what type of value a variable will contain when you declare (create and name) it.
- The same variable can hold different types of values at different times.
In contrast, many other programming languages (like Java, C++, or C#) are strongly-typed. You must declare what type of value a variable will hold. And trying to put a different type of value in the variable will cause an error.
JavaScript’s loosely-typed nature makes it more flexible. But it can make it harder to find errors - and can create unexpected behaviours! See the Testing for weird values Tutorial.
Because of these challenges, Microsoft created TypeScript, a programming language that adds data type checking to JavaScript. You can think of TypeScript as JavaScript+. It is increasingly popular for large-scale applications.
Try it yourself
In your workfile, declare and assign some more variables of different data types, and output them with template literals to your web browser console.
More learning resources
Tutorial Quiz
Tutorial Podcast
Sample AI prompts
What are some common mistakes developers make when naming variables? Can you show examples of good and bad practices?
Please provide a short and simple explanation of these four variable types in JavaScript and show some everyday examples of each:
- string
- numeric
- boolean
- null
I'm confused about when to use const
versus let
. Can you give me some real-world examples that make the difference clear? Limit your responses variables only. Do not include arrays or objects.
What would happen if I tried to change a value stored in a const
variable? Can you show me with examples?
What is meant by saying that JavaScript is a loosely-typed programming language?