Variables(var/let/const)

Learn what JavaScript variables are, how to declare them using let, const, and var, and how to store and update data in your programs.

What is a JavaScript Variable?Link to this section

A variable is a named container used to store data in computer memory. Think of it like a labeled storage box where you can keep values like numbers, words, or lists and use them later in your program.

We stored the number 10 inside a variable named score and then printed it.

  • `let` is the **keyword** used to declare the variable.
  • `score` is the **identifier** or name of the variable.
  • `=` is the **assignment operator** that puts the value into the container.
  • `10` is the **value** stored inside the variable.

Variables are used everywhere in programming to remember information while the code runs.

Why Do We Need JavaScript Variables?Link to this section

Without variables, you could only write code with fixed numbers and text that can never change or be reused.

  • Store user login names to display on a profile page.
  • Keep track of shopping cart totals in an online store.
  • Calculate and save a student test score average.
  • Remember if a dark mode toggle switch is turned on or off.
  • Count how many times a user clicks a button.
  • Hold temporary data during a complex math calculation.

Variables let us store item prices and tax amounts, calculate the total, and reuse those values.

We store individual pieces of data in variables so we can combine them, update them, and display the final result to the user.

About JavaScript VariablesLink to this section

Variables in JavaScript can hold different types of data such as numbers, strings, and booleans. Modern JavaScript gives us three ways to declare variables: let, const, and var. Each keyword has specific rules about whether the stored value can be changed later and how the variable is scoped within the code.

KeywordCan Reassign?Can Redeclare?Scope
letYesNoBlock scope
constNoNoBlock scope
varYesYesFunction scope

Constants cannot change after being set, while let variables can be updated.

Types and Declaration Methods of JavaScript VariablesLink to this section

1. The `let` KeywordLink to this section

The let keyword is used to declare variables whose values can be changed later in your program. It is the most commonly used keyword for regular variables like counters and user inputs.

We declare playerLevel as 1, then update it to 2.

Practical example of adding reward coins to a user account.

tip

Always use `let` when you know the value of your variable will need to change as the program runs.

warning

You cannot declare the same variable name twice using `let` in the same scope.

2. The `const` KeywordLink to this section

The const keyword stands for constant and is used for values that should never change once they are set. Trying to reassign a const variable will cause an error.

Birth years do not change, so we use const.

Using const for a fixed tax rate in a billing system.

note

If you try to reassign a `const` variable, JavaScript will throw a TypeError.

warning

You must always assign a value when declaring a `const` variable. Leaving it empty is a syntax error.

3. The `var` KeywordLink to this section

The var keyword is the older way to declare variables in JavaScript. It behaves differently than let and const regarding scope and allows redeclaration without errors.

Declaring a string variable using var.

Var allows redeclaring the same variable name without throwing an error.

warning

Avoid using `var` in modern code because its scoping rules can cause confusing bugs and unexpected global variables.

4. Declaring Without a Keyword (Implicit Globals)Link to this section

Writing a variable name and assigning a value without let, const, or var creates an implicit global variable. This is strongly discouraged in modern JavaScript.

Creating a variable without a keyword.

warning

Always use a declaration keyword. Omitting keywords pollutes the global scope and leads to silent bugs, especially in strict mode.

5. Declaring Multiple VariablesLink to this section

You can declare multiple variables in a single statement by separating them with commas. This is helpful for grouping related variables together.

Declaring three variables in one line using commas.

tip

While declaring multiple variables on one line is compact, many developers prefer putting each on its own line for better readability.

6. Uninitialized VariablesLink to this section

When you declare a variable using let or var without giving it a value, JavaScript automatically assigns it the special value undefined.

Variables declared without an initial value default to undefined.

note

`undefined` means a variable has been declared but has not yet been assigned a value.

Variable Naming Rules and Best PracticesLink to this section

JavaScript has strict rules on what you can name your variables. Following naming conventions makes your code readable and prevents syntax errors.

Rule / PracticeAllowed?Example
Starts with letterYeslet name = "Alice";
Starts with numberNolet 1st = 1;
Uses camelCaseRecommendedlet totalScore = 50;
Reserved keywordsNolet let = 5;

Valid variable names can contain letters, numbers, dollar signs, and underscores.

warning

Variable names cannot start with a number.

tip

Use camelCase for variable names (e.g., `userLoginStatus` instead of `user_login_status`).

Complete Coding ExampleLink to this section

This program combines constants, let variables, math calculations, and output strings into a complete receipt system.

This script uses constants for store info and let variables for customer data and billing calculations, showcasing how variables work together in a real program.

Important NotesLink to this section

  • A variable is a named container for storing data in memory.
  • Use `let` for variables whose values will change later.
  • Use `const` for values that should remain constant throughout the program.
  • Avoid using `var` in modern JavaScript code due to scoping issues.
  • Variables declared with `let` or `var` without values default to `undefined`.
  • Constants (`const`) must always be given a value when declared.
  • Variable names are case-sensitive (`Score` and `score` are different).
  • Names can contain letters, numbers, underscores, and dollar signs.
  • Names cannot start with a number or use reserved JavaScript keywords.
  • Always use descriptive variable names like `userAge` instead of single letters like `x`.

SummaryLink to this section

In this lesson, you learned what JavaScript variables are and why they are essential for storing and managing data. You explored how to declare variables using let, const, and var, along with the rules for naming them properly. Mastering variables is your first big step toward building interactive and dynamic programs.

Check Your UnderstandingLink to this section

Javascript Variables quiz
Question 1 of 6

Which keyword should you use for a variable whose value will never change?

Practice ChallengesLink to this section

1. Create a Greeting

easy

Declare a const variable for your first name and a let variable for your greeting message. Print both to the console.

Expected output

Alice Welcome

Hint: Use const for the name and let for the message.

2. Calculate Total Price

easy

Create two variables: itemPrice set to 30 and shippingFee set to 5. Calculate the sum in a third variable called total and print it.

Expected output

35

Hint: Add itemPrice and shippingFee together using the + operator.

3. Update Player Score

medium

Declare a variable score with an initial value of 100 using let. Update the score by adding 50 points, then print the new score.

Expected output

150

Hint: Reassign score using score = score + 50.

4. Store User Profile

medium

Create three variables to hold a user profile: username (string), userAge (number), and isLoggedIn (boolean). Print all three values.

Expected output

John 28 true

Hint: Declare each with let and separate them or print them on separate lines.

5. Temperature Converter

hard

Create a const variable for a temperature in Celsius (e.g., 25). Calculate Fahrenheit using the formula (celsius * 9/5) + 32 and store it in a let variable. Print the final Fahrenheit value.

Expected output

77

Hint: Follow the mathematical formula step by step.

Rate this content

Sign in to rate

Discussion

Sign in to join the discussion