DEV Community

Cover image for Understanding JavaScript Variables
Richa
Richa

Posted on

Understanding JavaScript Variables

Introduction

Variables in JavaScript are like containers that store data. Think of them as labeled jars in your kitchen – some hold sugar, some hold flour, and some even hold cookies!πŸͺ They make your code dynamic and enable you to store and manipulate information.

⭐ Variable Declaration, Initialization, and Naming Conventions
1️⃣ Declaration
Declaring a variable means creating it without assigning a value.
πŸ“Œ Example:

let name; // Declaration
Enter fullscreen mode Exit fullscreen mode

2️⃣ Initialization
Initializing a variable means assigning it a value for the first time.
πŸ“Œ Example:

let name = "Richa"; // Declaration + Initialization
Enter fullscreen mode Exit fullscreen mode

You can also declare first and initialize later:
πŸ“Œ Example:

let age; // Declaration
age = 25; // Initialization
console.log(age); // Outputs: 25
Enter fullscreen mode Exit fullscreen mode

3️⃣ Naming Conventions
Follow these rules to name variables effectively:

  • Start with a letter, $, or _. Valid: userName, _temp, $amountInvalid: 123name, @value
  • Avoid reserved keywords: Invalid: let var = 10; (cannot use var as a name)
  • Use camelCase for readability: Example: firstName, totalCost
  • Be descriptive: Instead of x, use userAge or productName.

πŸ“Œ Example:

let userName = "John"; // Descriptive and camelCase
const MAX_USERS = 100; // Use uppercase for constants
let _tempValue = 42; // Valid use of underscore
let $price = 99.99; // Valid use of $
Enter fullscreen mode Exit fullscreen mode

⭐Types of Variables
JavaScript offers three ways to declare variables: var, let, and const.

1️⃣ var (Old-School)
Scope: Function-scoped or globally scoped.
Usage: Best avoided in modern JavaScript due to its quirks.
The var keyword was prevalent in JavaScript before 2015. However, it is less recommended now because of its global scope and hoisting behavior.
πŸ“Œ Example:

var stuff = "Toy";
var stuff = "Book"; // Re-declaration allowed (confusing behavior).
console.log(stuff); // Outputs: Book
Enter fullscreen mode Exit fullscreen mode

With var, you can declare the same variable multiple times. However, this often leads to bugs and confusing code.
⁉️Hoisting Behavior:
Variables declared with var are "hoisted", meaning you can use them before declaring them.
πŸ“Œ Example:

console.log(stuff); // Outputs: undefined
var stuff = "Toy";
Enter fullscreen mode Exit fullscreen mode

This behavior can result in unexpected issues, so avoid relying on var for variable declarations.
πŸ‘‰A Real-World Example
var (Old-School)

2️⃣ let (Flexible)
Scope: Block-scoped (limited to the block it’s declared in).
Usage: Use let when the variable value needs to change.
πŸ“Œ Example:

let jar = "Tomatos";
jar = "Spices"; // Allowed
console.log(jar); // Outputs: Spices
Enter fullscreen mode Exit fullscreen mode

Attempting to re-declare a let variable will throw an error:
πŸ“Œ Example:

let jar = "Tomatos";
let jar = "Spices"; // Error: Identifier 'jar' has already been declared
Enter fullscreen mode Exit fullscreen mode

Unlike var, variables declared with let are not hoisted in the same way:
πŸ“Œ Example:

console.log(jar); // ReferenceError: Cannot access 'jar' before initialization
let jar = "Tomatos";
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰A Real-World Example
let (Flexible)

3️⃣ const (Immutable)
Scope: Block-scoped, like let
Usage: Use const for values that should not change after being initialized.
const is perfect for declaring constants or variables that shouldn’t be reassigned.
πŸ“Œ Example:

const packet = "Milk";
packet = "Juice"; // Error: Assignment to constant variable
Enter fullscreen mode Exit fullscreen mode

You must initialize a const variable when declaring it:
πŸ“Œ Example:

const packet; // Error: Missing initializer in const declaration
Enter fullscreen mode Exit fullscreen mode

πŸ‘‰A Real-World Example
const (Immutable)

Tasks to Explore Variables

Here are some examples to test your understanding of variables:

/* Task 1: */ 
let age = 4;
console.log(age); // Outputs: 4

/* Uncomment the following to see errors: */
/* const age = 10; // SyntaxError: Identifier 'age' has already been declared */

/* Task 2: */
const salary = 2000; // Correct
console.log(salary);

/* Task 3: */
/* const salary; // SyntaxError: Missing initializer in const declaration */

/* Task 4: */
/* const salary = 0;
console.log(salary);
salary = 10; // TypeError: Assignment to constant variable */
Enter fullscreen mode Exit fullscreen mode

Conclusion

Mastering variables is the first step toward writing clean and efficient JavaScript code.

  • Use const whenever possible for stability.
  • Use let only when the value needs to change.
  • Avoid var to prevent hard-to-debug issues.

Happy coding! πŸŽ‰

Top comments (0)