Labs ICT
Pro Login

Variables (var, let, const)

Variables are containers for storing data values. In JavaScript, you can declare variables using three keywords: var, let, and const.

Declaring Variables

Using let (Recommended)

The let keyword was introduced in ES6 and is the preferred way to declare variables that will be reassigned.

let age = 25;
console.log(age); // Outputs: 25

age = 26; // Can be reassigned
console.log(age); // Outputs: 26

Using const

The const keyword is used for variables that should not be reassigned. The value cannot be changed once assigned.

const PI = 3.14159;
console.log(PI); // Outputs: 3.14159

// PI = 3.14; // Error: Assignment to constant variable

Using var (Legacy)

The var keyword is the old way of declaring variables. It has some issues with scope and hoisting, so it's generally avoided in modern JavaScript.

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

Variable Naming Rules

When naming variables, follow these rules:

  • Must start with a letter, underscore (_), or dollar sign ($)
  • Cannot start with a number
  • Can contain letters, numbers, underscores, and dollar signs
  • Are case-sensitive (age and Age are different variables)
  • Cannot use reserved keywords
// Valid variable names
let firstName = "John";
let last_name = "Doe";
let $price = 100;
let _private = "secret";
let age123 = 25;

// Invalid variable names
// let 123age = 25; // Cannot start with number
// let first-name = "John"; // Hyphen not allowed
// let class = "student"; // Reserved keyword

Variable Scope

Block Scope (let and const)

Variables declared with let and const have block scope, meaning they only exist within the block they are defined in.

{
  let blockVariable = "I'm inside a block";
  console.log(blockVariable); // Outputs: I'm inside a block
}

// console.log(blockVariable); // Error: blockVariable is not defined

Function Scope (var)

Variables declared with var have function scope, meaning they exist throughout the entire function.

function testScope() {
  if (true) {
    var functionVariable = "I'm in function scope";
  }
  console.log(functionVariable); // Outputs: I'm in function scope
}

testScope();
// console.log(functionVariable); // Error: functionVariable is not defined

Hoisting

JavaScript hoists variable declarations to the top of their scope, but not their assignments.

// var is hoisted with undefined value
console.log(hoistedVar); // Outputs: undefined
var hoistedVar = "I'm hoisted";

// let and const are hoisted but not initialized (Temporal Dead Zone)
// console.log(hoistedLet); // Error: Cannot access 'hoistedLet' before initialization
let hoistedLet = "I'm also hoisted";

Data Types

JavaScript variables can hold different types of data:

// Numbers
let age = 25;
let price = 19.99;

// Strings
let name = "John Doe";
let message = 'Hello, World!';

// Booleans
let isStudent = true;
let isWorking = false;

// Undefined
let undefinedVar;
console.log(undefinedVar); // Outputs: undefined

// Null
let nullVar = null;
console.log(nullVar); // Outputs: null

// Objects
let person = {
  firstName: "John",
  lastName: "Doe",
  age: 25
};

// Arrays
let colors = ["red", "green", "blue"];

Multiple Variable Declaration

You can declare multiple variables in a single statement:

// Multiple declarations with different values
let firstName = "John", lastName = "Doe", age = 25;

// Multiple declarations with same value
let x = 5, y = 5, z = 5;

// Mixed declaration types
const PI = 3.14159;
let radius = 10;
var diameter = 20;

Constants and Objects

When using const with objects, the object reference cannot be changed, but the object properties can be modified:

const person = {
  name: "John",
  age: 25
};

// This is allowed - modifying properties
person.age = 26;
person.city = "New York";

// This is not allowed - reassigning the constant
// person = { name: "Jane", age: 30 }; // Error

let vs const vs var - When to Use Each

Keyword Scope Can Reassign When to Use
const Block No Default choice, when value won't change
let Block Yes When value needs to be reassigned
var Function Yes Legacy code, avoid in new code

Best Practices

✓ Do:

  • Use const by default, let when you need to reassign
  • Use descriptive variable names
  • Use camelCase for variable names
  • Declare variables at the top of their scope
  • Initialize variables when you declare them

✗ Don't:

  • Use var in new code
  • Use single-letter variable names (except for counters)
  • Start variable names with uppercase (that's for classes)
  • Use reserved keywords as variable names
  • Declare variables without initializing when possible

Complete Example

// A complete example showing best practices
const API_URL = "https://api.example.com";
let currentUser = null;
let isLoggedIn = false;

function login(username, password) {
  // Simulate API call
  const userData = {
    id: 1,
    name: username,
    email: username + "@example.com"
  };
  
  currentUser = userData;
  isLoggedIn = true;
  
  return userData;
}

function logout() {
  currentUser = null;
  isLoggedIn = false;
}

// Usage
const user = login("johndoe", "password123");
console.log("Logged in user:", user);

logout();
console.log("Current user:", currentUser); // null