JavaScript Lesson 3 - Variables | Dataplexa

Variables

In everyday life, we remember information all the time. A price, a name, a phone number, or a total amount.

In JavaScript, variables are used for the same purpose — to store information so the program can use it later.


Real-World Example

Imagine you are building a simple shopping website. When a customer adds a product to the cart, you need to remember:

  • The product name
  • The price
  • The quantity

If JavaScript could not store these values, the cart would reset every time the page changes. Variables help JavaScript remember data while the program is running.


What Is a Variable?

A variable is a container that holds a value. This value can be used, updated, or read whenever needed.

You can think of a variable like a labeled box. The label is the variable name, and the box holds the value.


Ways to Create Variables in JavaScript

JavaScript provides three keywords to create variables:

  • var – old method (not recommended)
  • let – modern and commonly used
  • const – used for fixed values

Using let

Use let when the value may change later.


let totalAmount = 500;
totalAmount = 650;
  

Here, the value changes from 500 to 650. This is common in real applications such as shopping carts or billing systems.


Using const

Use const when the value should not change.


const companyName = "Dataplexa";
  

If you try to change a const value, JavaScript will throw an error. This helps prevent accidental changes.


Using var (Why It Is Avoided)

var is the older way of creating variables. It can lead to unexpected behavior and bugs in larger programs.


var count = 10;
  

In modern JavaScript, let and const are preferred because they are safer and easier to manage.


Thumb Rules

  • Use let if the value needs to change
  • Use const for values that should remain fixed
  • Avoid var in new projects
  • Use clear and meaningful variable names

Common Beginner Mistakes

  • Using unclear names like x or temp
  • Trying to change a const value
  • Using var without understanding its behavior

More on Variables Later

In this lesson, we focused on understanding what variables are and how to use them in a simple and practical way.

Some important details about variables are intentionally kept simple for now so you can build confidence step by step.

You will learn more about:

What Comes Next?

Now that you know how JavaScript stores values using variables, the next step is understanding the different types of data that variables can hold.

In the next lesson, we will explore JavaScript data types.