JavaScript  

Variables in JavaScript

In every programming language, a variable is akin to a labeled container that stores a value. Whether it's JavaScript, Python, C++, or Java, variables are used to store data such as numbers, text, or objects so the program can use and modify that data during execution.

A variable is a symbolic name that references a location in memory where data is stored. It allows programs to store dynamic values and manipulate them during execution.

A variable in JavaScript is a named storage container that holds a value such as a number, string, object, or function, which we can use, update, or reuse later in our program. Imagine your kitchen.

  • You have jars labeled "Sugar," "Salt," and "Tea."
  • Each jar stores a different item, and you can change the contents at any time (e.g., refill the sugar jar or replace it with something else).
  • The label on the jar is like the variable name, and the thing inside is the value.

In JavaScript.

let userName   = "Bertin";
let age        = 25;
let isLoggedIn = true;
  • We store a name, age, and login status using variables.
  • Later in the program, we can refer to userName, age, or isLoggedIn without rewriting the actual values.

In JavaScript, variables can be declared using.

Keyword Description When to Use
var The original way to declare variables in JavaScript. It is function-scoped and can be redeclared, reassigned, and hoisted to the top of the function. Use in legacy (old) JavaScript code only. Avoid in modern development.
let Modern variable declaration. Block-scoped (only accessible within {}), can be reassigned but not redeclared in the same block. Use when the value needs to change (like counters, loops, toggles).
const Modern declaration for constants. Block-scoped like let, but cannot be reassigned or redeclared. Must be initialized at the time of declaration. Use when the value should never change (such as configuration values or fixed IDs).

Const, let, and var are all keywords in JavaScript. A keyword is a reserved word in the JavaScript language that has a special meaning and cannot be used as an identifier (e.g., variable name, function name, etc.).

Importance of Variables in Programming

Variables are named containers in memory that hold values that can be used, updated, and passed throughout a program. Now let’s explore why variables are critically crucial in programming:

  1. Data Storage: Store temporary data, such as numbers, strings, or objects.
  2. Code Flexibility: Change behavior dynamically (e.g., setting discount to 10 can be adjusted based on user role).
  3. Readability: Using descriptive variable names (userAge instead of x) makes the code self-explanatory.
  4. Reuse & Efficiency: Once declared, the same variable can be used multiple times instead of repeating values.

Think of a shopping list. Instead of writing "Apples - 10" everywhere, we can define it.

let apples = 10;

And use apples wherever needed.

Types of Variables in JavaScript

1. var

var name = "Daniel";
name = "Prince";
var name = "Mich"; // Allowed (but bad practice)

In this code, we declare a variable named " Alice " and assign it "Alice", we reassign it to "Bob", which is valid, and then re-declare the same variable using var and assign "Charlie". This is technically allowed with var, but it's a bad practice, as it can lead to confusion and accidental overwrites.

Think of a shared notice board in an office.

  • First, a note titled "name" is pinned with the message "Alice".
  • Later, it's updated to "Bob".
  • Then another note titled "name" is added with "Charlie".

Since everyone can modify the board, the same name appears multiple times with different values, making it difficult to trust or understand the board.

2. let

let age = 25;
age = 30;

// let age = 35; // Error - already declared

In this code, we declare a variable age and assign it the value 25. We then update the value to 30, which is allowed, and trying to re-declare age using let in the same block throws an error.

This is like writing "Age: 25" in a personal notebook.

  • Later, we update that page to "Age: 30", which is perfectly fine.
  • But trying to create another page in the same notebook titled "Age" results in duplication and confusion and is not allowed.

let prevents re-declaration to keep our code clean and error-free.

3. const

const city = "Tenkasi";
// city = "Nellai"; // Error - cannot reassign

In this code, we declare a constant variable named city and assign it the value "Delhi". Attempting to reassign it to "Mumbai" causes an error because continuous variables cannot be reassigned.

Think of a passport where the city of issue is printed as "Chennai".

  • Once printed, that city cannot be changed.
  • The value remains constant throughout the program.

Difference between var, let, and const

Feature var (Old Way) let (Modern Way) const (Fixed Value)
Can it Change the Value? Yes — we can update it anytime Yes — we can update it No — once set, the value cannot change
Can I rename again? Yes — we can declare it again (not good practice) No, cannot re-declare in the same block No, cannot re-declare in the same block
Scope (Where it works) Function-level (works inside the entire function) Block-level (works only inside { }) Block-level (same as let)
Hoisting (Early Use) Yes — moved to top and becomes undefined No — using before declaring causes an error No — same error as let (called Temporal Dead Zone error)
Can Change Inside? Yes — works for arrays/objects Yes — same as var Yes — object/array contents can change, name cannot
Best Use Case For old code, not used in new projects For general variables (numbers, text, objects, etc.) For constants like MAX_USERS = 10 or config settings
Common Issues Overwritten easily, confusing scope (avoid if possible) Safer and easier to understand Cannot change — good for safety and clarity

Naming Conventions in JavaScript Variables

  1. Use camelCase for variable names. Start with a lowercase letter, and capitalize the first letter of each new word. This is the standard practice in JavaScript.
  2. Use meaningful and descriptive names. A variable name should clearly describe the data it stores. This helps others (and ourselves) understand the purpose of the variable without having to guess.
  3. Avoid using single letters or short, generic names like 'x', 'a, or 'temp', unless working with loops or temporary throwaway values.
  4. Do not use JavaScript reserved keywords (like return, let, class) as variable names. They are reserved for JavaScript’s internal use.
  5. Use all UPPERCASE letters with underscores (UPPER_SNAKE_CASE) for constant values that are fixed and should not be changed once assigned, such as configuration values or limits.
  6. Boolean variable names (those storing true/false values) should start with words like is, has, or can to indicate their intent clearly, for example, isActive, hasPermission, canSubmit.
  7. Use plural names for arrays. If a variable stores multiple items, the name should reflect that, like users, products, or tasks, so it’s clear that the variable holds a collection.
  8. Use nouns for variables and verbs for functions. Variables store data (things), while functions perform actions (do things).
  9. Keep naming consistent throughout a project. Following the same style across all files and modules helps in easier reading and maintenance.

Conclusion

Through this topic, we’ve understood that variables are the foundation of all logic in JavaScript. They are not just memory references but key components that define how data flows and behaves in a program. Choosing the right keyword (var, let, or const) and following proper naming conventions improves the clarity, safety, and professionalism of our code.