Home Courses Variables Explained in Depth - var, let, const

Variables Explained in Depth - var, let, const

What are Variables?

Variables are containers.

They store information like name, age, score, etc.

Simple idea:

A variable is like a box that stores data.


Why we use Variables?

We use variables to store data so we can use it later.

Examples:

  1. Login form (username, password)
  2. Show message like "Welcome userName"
  3. Game score changes
  4. Shopping cart items

First store data, then use it.


Types of Variables

There are 3 types:

  1. var (old)
  2. let (recommended)
  3. const (fixed value)


Basic Difference

  1. var and let → value can change
  2. const → value cannot change

Example:


let name = "Anil";
name = "Peter"; // allowed

const city = "Delhi";
city = "Mumbai"; // not allowed


Syntax (How to create variable)


let data = "Anil";

  1. let → type
  2. data → variable name
  3. "Anil" → value


Important Rules (Naming)

You can use:

  1. letters (a to z)
  2. numbers (not at start)
  3. underscore (_)
  4. dollar ($)

Not allowed:

  1. space in name
  2. starting with number
  3. keywords like var, let, const


Best Practice

  1. Use let when value changes
  2. Use const when value is fixed
  3. Avoid var

Use meaningful names:


let userName = "Anil"; // good
let x = "Anil"; // not good


Why avoid var?

  1. Can declare same variable again
  2. Creates confusion
  3. Scope issues


Variable Value Change Example


let data = "Anil";
data = "Sameer"; // value changed


Const Example (Error Case)


const data = "Anil";
data = "Peter"; // error

Once value is set, it cannot change.


Data Stored in Variables

You can store:

  1. name
  2. number
  3. address
  4. any information


Code


<html>
<head>
<script>
let userName = "anil"
alert(userName)
</script>
</head>
<body>
<h1>Variables</h1>
</body>
</html>

What this code does:

  1. Creates a variable userName
  2. Stores value "anil"
  3. Shows alert with "anil"


Share this lesson: