JavaScript Variables

JavaScript Variables

JavaScript Variables

What are Variables?

Variables in JavaScript are containers for storing data values. They allow us to store, update, and manipulate data in our programs.

1️⃣ Declaring Variables in JavaScript

JavaScript provides three ways to declare variables:

KeywordScopeReassignmentHoistingMutable
varFunction-scoped✅ Yes✅ Yes✅ Yes
letBlock-scoped✅ Yes❌ No✅ Yes
constBlock-scoped❌ No❌ No❌ No

🔹 Using var (Old Way, Avoid Using)

var name = "John"; console.log(name); // John

🚨 Problems with var:

  • Function-scoped (not block-scoped)
  • Can be redeclared and overwritten, which can lead to bugs
  • Gets hoisted (moved to the top of its scope), but initialized as undefined

🔹 Using let (Recommended)

let age = 25; age = 30; // ✅ Allowed console.log(age); // 30

Better than var because:

  • Block-scoped (only accessible inside {} where it was declared)
  • Cannot be redeclared within the same scope

🔹 Using const (Best for Constants)

const PI = 3.14; PI = 3.1415; // ❌ ERROR: Assignment to constant variable.

Use const when:

  • The value should not change
  • You are working with constant values

📌 Note: If you declare an object or array with const, you can modify its properties but cannot reassign it.

const person = { name: "Alice" }; person.name = "Bob"; // ✅ Allowed (modifying property) person = { name: "Charlie" }; // ❌ ERROR: Cannot reassign a const object

2️⃣ Variable Naming Rules

✅ Can contain letters, digits, _, and $
✅ Must start with a letter, _, or $
Cannot start with a digit
Cannot use reserved keywords like let, var, const, function, etc.

let _username = "John"; // ✅ Allowed let $price = 100; // ✅ Allowed let 1number = 5; // ❌ ERROR: Cannot start with a number

3️⃣ Hoisting in JavaScript

  • var is hoisted but initialized as undefined
  • let and const are hoisted but not initialized, causing a ReferenceError if accessed before declaration.
console.log(a); // ✅ Undefined (because `var` is hoisted) var a = 10; console.log(b); // ❌ ERROR: Cannot access 'b' before initialization let b = 20;

4️⃣ Dynamic Typing (No Need to Specify Type)

JavaScript is dynamically typed, meaning variables do not have a fixed type.

let x = 5; // Number x = "Hello"; // String (allowed) x = true; // Boolean (allowed) console.log(x); // true

🎯 Summary

✅ Use let for the variables that will change
✅ Use const for constants that won’t change
✅ Avoid var (due to scoping issues)
✅ JavaScript variables do not have fixed types
✅ Variables must be declared before use

🚀 Now you’re ready to use JavaScript variables like a pro! Let me know if you need more details. 😊

Soeng Souy

Soeng Souy

Website that learns and reads, PHP, Framework Laravel, How to and download Admin template sample source code free.

Post a Comment

CAN FEEDBACK
close