JavaScript Variables

In JavaScript, variables are containers for storing data values. You can use variables to hold numbers, strings, booleans, objects, and more. JavaScript uses the var, let, and const keywords to declare variables.

Here are some common uses of variables:

  • Store data: Variables hold values you want to use later in your program.
  • Reuse data: Access the same value multiple times by referring to the variable.
  • Manipulate data: Update or calculate values stored in variables.
  • Improve readability: Descriptive variable names make code easier to understand.


What You'll Learn

You'll learn how to declare, assign, and use variables in JavaScript. This includes understanding the difference between var, let, and const, and the best practices when naming variables.


Declaring Variables

To create a variable in JavaScript, use one of the following keywords:

javascript
let x = 5;
const y = 10;
var z = 15;
  • let: Used when you want to create a variable that can change its value later. For example, you can set x to 5, and later change it to 10.
  • const: Used for values that should never change. Once you set a const variable, its value stays the same forever. For example, once y is set to 10, you can't change it.
  • var: This is an old way of creating variables. It can change values, just like let. However, it has some problems, like letting you accidentally create the same variable multiple times in the same place (which can lead to bugs). For example, you can do: var z = 10; var z = 20;. This would not cause an error, but it can lead to unexpected behavior. It's better to use let or const in modern code.

Rules for Naming Variables

In JavaScript, variable names must follow these rules:

  1. Variable names must start with a letter, an underscore _, or a dollar sign $.
    Example of valid names: _myVar, $value, name.
  2. Variable names cannot start with a number.
    Example of invalid name: 1value (this will throw an error).
  3. Variable names can include letters, numbers, underscores _, or dollar signs $.
    Example of valid names: user_1, price$, myVar2.
  4. Variable names cannot be JavaScript reserved keywords, such as let, if, class, or function.
    Example of invalid names: let, return, while.
  5. Variable names are case-sensitive. This means myVar and MyVar are different variables.
    Example: myVar and MyVar are two separate variables.
  6. Variable names cannot contain spaces.
    Example of invalid name: my variable.
    Example of valid name: myVariable or my_variable.
  7. Variable names can include Unicode characters.
    Example: let π = 3.14; (though this is rare and not commonly used).
  8. Variable names should be meaningful to improve code readability and maintenance.
    Example: userAge is better than x.

Example 1: Declaring and Printing a Variable

To declare a variable and print it, you can use the let keyword to declare the variable and console.log() to display it on the screen.

javascript
let name = "Peter";
console.log(name);

How It Works:

  • let: This is the JavaScript keyword used to declare a variable that can be changed later.
  • name: This is the name of the variable where the value is stored. You can choose any valid name for your variable.
  • "Peter": This is the value assigned to the variable name. It’s a string enclosed in double quotes.
  • console.log(): This is the JavaScript function used to display the value of a variable or message on the screen.
  • When the code is run, JavaScript takes the value of the name variable ("Alice") and prints it on the screen using console.log().

Output

Peter

Example 2: Reassigning a Variable

In this example, we declare a variable and then change its value:

javascript
let age = 20;
age = 21;
console.log(age);

How It Works:

  • let: Used to declare the variable age, which can be reassigned later.
  • age = 20: Initially, we assign the value 20 to the age variable.
  • age = 21: Later, we reassign the value of the age variable to 21.
  • console.log(): This prints the updated value of age, which is now 21, on the screen.

Output

21

Example 3: Using a Constant Variable

In JavaScript, you can use the const keyword to declare a variable whose value cannot be reassigned after it's set.

javascript
const pi = 3.14;
console.log(pi);

How It Works:

  • const: This keyword is used to declare a variable whose value cannot be reassigned after the initial assignment.
  • pi: This is the name of the constant variable where the value of Pi is stored.
  • 3.14: This is the value assigned to the pi variable. It is a number that represents the mathematical constant Pi.
  • console.log(): This is used to print the value of the pi variable on the screen.
  • When the code is run, JavaScript will print the value of Pi (3.14) on the screen. Note that if you try to change the value of pi later, JavaScript will throw an error.

Output

3.14

Exercises

Try these exercises to practice working with JavaScript variables:

1. Store your favorite food in a variable and print it.
javascript
// Exercise 1. Store your favorite food in a variable and print it.
let favoriteFood = "Pizza";
console.log(favoriteFood);

2. Create a variable to store your age, then print it.
javascript
// Exercise 2. Create a variable to store your age, then print it.
let age = 25;
console.log(age);

3. Reassign a value to a variable and print the result.
javascript
// Exercise 3. Reassign a value to a variable and print the result.
let city = "New York";
city = "London";
console.log(city);

*Tip: Try experimenting with different types of values like numbers, strings, and booleans.


Frequently Asked Questions

What are variables in JavaScript?

Variables in JavaScript are containers used to store data values, such as numbers, strings, booleans, or objects. They allow developers to reuse and manipulate data within a program.


What is the difference between var, let, and const?

var is the older way to declare variables and is function-scoped. let is block-scoped and allows reassignment. const is also block-scoped but cannot be reassigned once a value is set.


When should I use let or const?

Use const by default for variables that don’t need to change. Use let when you know the value will change later. Avoid using var in modern JavaScript as it can cause scoping issues.


Can I change the value of a const variable?

No, const variables cannot be reassigned after they are declared. Attempting to do so will result in an error.


What are the rules for naming JavaScript variables?

Variable names must start with a letter, underscore (_), or dollar sign ($). They can't begin with a number or use reserved keywords, and they are case-sensitive.



What's Next?

Next, you'll learn about JavaScript data types such as strings, numbers, arrays, and objects—key to working effectively with variables.