JavaScript Variables

In JavaScript, variables are used to store data values that can be used and manipulated later in the program. Think of a variable as a container that holds information.

Variable Naming Rules

  1. Names can contain letters, digits, underscores ( _ ), and dollar signs ($).
  2. Must start with a letter, $, or _.
  3. Case-sensitive (e.g., myName and myname are different).
  4. Cannot use reserved keywords (like let, class, if, etc.).

Example:

let myName = "Alice";
let $price = 100;
let _value = 50;

Declaring Variables

JavaScript provides three keywords to declare variables:

  1. var: The old way (not commonly used anymore).
  2. let: The modern way, allows variable re-assignment.
  3. const: Used for variables that should not be re-assigned

1. Using var

  • Can be re-declared and updated.
  • Not recommended for modern coding because of its scope issues.

Example:

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

2. Using let

  • Can be updated but cannot be re-declared within the same scope.
  • Block-scoped (only works inside the block it’s defined).

Example:

let age = 25;
console.log(age); // Output: 25
age = 30; // Updating the value
console.log(age); // Output: 30

3. Using const

  • Cannot be updated or re-declared.
  • Must be initialized when declared.
  • Used for values that should stay constant (like PI or configurations).

Example:

const pi = 3.14;
console.log(pi); // Output: 3.14
// pi = 3.15; // Error: Assignment to constant variable.

Scope of Variables

  1. Global Scope: A variable declared outside functions is accessible everywhere.
  2. Function Scope: A variable declared inside a function is only accessible within that function.
  3. Block Scope: Variables declared with let and const are limited to the block {}.

Example:

function testScope() {
  let localVariable = "I exist only inside this function!";
  console.log(localVariable);
}
// console.log(localVariable); // Error: localVariable is not defined

Best Practices

  1. Use const by default, and switch to let only when you need to reassign.
  2. Avoid using var.
  3. Use meaningful variable names that describe their purpose.

Code Example: Putting It All Together

// Using const for constant values
const pi = 3.14;

// Using let for variables that can change
let radius = 5;
let area = pi * radius * radius;

console.log("Area of the circle:", area); // Output: Area of the circle: 78.5

// Using var (not recommended)
var greeting = "Hello, JavaScript!";
console.log(greeting); // Output: Hello, JavaScript!

// Demonstrating scope
if (true) {
let scopedVar = "I am inside a block!";
console.log(scopedVar); // Output: I am inside a block!
}
// console.log(scopedVar); // Error: scopedVar is not defined

Leave a Reply

Your email address will not be published. Required fields are marked *