Home ยป JavaScript Variables: A Complete Tutorial with Examples

JavaScript Variables: A Complete Tutorial with Examples

In JavaScript, variables are used to store data that can be referenced and manipulated throughout a program. They act as containers for data values and play a fundamental role in programming.

This tutorial will guide you through the basics of declaring and using variables in JavaScript, covering different types of variables and how to use them effectively.

1. Declaring Variables

JavaScript provides three keywords for declaring variables: var, let, and const.

1.1. Using var

The var keyword is the oldest way to declare variables in JavaScript. Variables declared with var are function-scoped or globally scoped and can be reassigned.

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

name = 'Jane'; // Reassigning the variable
console.log(name); // Output: Jane

Explanation

The variable name is declared using var and initialized with the value ‘John'.
It is then reassigned to ‘Jane'.

1.2. Using let

Introduced in ES6 (ES2015), let is the modern way to declare variables. Variables declared with let are block-scoped, meaning they are confined to the block {} in which they are declared.

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

age = 30; // Reassigning the variable
console.log(age); // Output: 30

Explanation

The variable age is declared using let and can be reassigned just like var.
However, let provides block-scoping, making it more predictable in certain contexts (e.g., inside loops or conditional statements).

1.3. Using const

const is also introduced in ES6 and is used to declare constants. Variables declared with const are block-scoped and cannot be reassigned.

const birthYear = 1990;
console.log(birthYear); // Output: 1990

// birthYear = 2000; // Error: Assignment to constant variable.

Explanation

The variable birthYear is declared using const and is initialized with the value 1990.

Attempting to reassign birthYear will result in an error since const variables cannot be reassigned.

2. Variable Naming Rules

Variable names can contain letters, digits, underscores (_), and dollar signs ($).
Variable names must not start with a digit.
JavaScript is case-sensitive, so myVariable and myvariable are considered different variables.
Variable names should be meaningful, indicating what data they represent.

Example 1: Valid Variable Names

let myVariable = 'Hello';
let _name = 'John';
let $amount = 100;
let firstName = 'Alice';

Example 2: Invalid Variable Names

// let 1name = 'John'; // Error: Variable name cannot start with a digit
// let my-variable = 10; // Error: Hyphens are not allowed in variable names

3. Variable Initialization and Declaration

A variable can be declared without being immediately assigned a value. Uninitialized variables have the value undefined.

Example 3: Variable Declaration and Initialization

let count; // Declaration
console.log(count); // Output: undefined

count = 5; // Initialization
console.log(count); // Output: 5

Explanation

count is declared but not initialized, so its value is undefined.
Later, count is assigned the value 5.

4. Different Types of Variables

Variables in JavaScript can hold different types of values, including numbers, strings, booleans, objects, and more.

4.1. Numbers

let score = 100;
let price = 29.99;
console.log(score); // Output: 100
console.log(price); // Output: 29.99

4.2. Strings

let greeting = 'Hello, World!';
let name = "Alice";
console.log(greeting); // Output: Hello, World!
console.log(name); // Output: Alice

4.3. Booleans

let isAvailable = true;
let isComplete = false;
console.log(isAvailable); // Output: true
console.log(isComplete); // Output: false

4.4. Objects

let person = {
  firstName: 'John',
  lastName: 'Doe',
  age: 30
};
console.log(person); // Output: { firstName: 'John', lastName: 'Doe', age: 30 }

4.5. Arrays

let colors = ['red', 'green', 'blue'];
console.log(colors); // Output: ['red', 'green', 'blue']

5. Scope of Variables

5.1. Global Scope

A variable declared outside of any function or block has a global scope. It is accessible from anywhere in the code.

var globalVar = 'I am global';

function printGlobalVar() {
  console.log(globalVar); // Output: I am global
}

printGlobalVar();
console.log(globalVar); // Output: I am global

5.2. Function Scope

Variables declared inside a function using var are function-scoped and are not accessible outside of the function.

function printLocalVar() {
  var localVar = 'I am local';
  console.log(localVar); // Output: I am local
}

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

5.3. Block Scope

Variables declared with let and const are block-scoped. They are only accessible within the block where they are declared.

if (true) {
  let blockVar = 'I am block-scoped';
  console.log(blockVar); // Output: I am block-scoped
}

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

6. Hoisting with Variables

JavaScript hoists variable declarations to the top of their scope. However, only the declaration is hoisted, not the initialization.

Example 4: Hoisting with var

console.log(hoistedVar); // Output: undefined
var hoistedVar = 'I am hoisted';

Explanation

The variable hoistedVar is hoisted to the top of its scope, but its value is not initialized until the line var hoistedVar = ‘I am hoisted';.

Example 5: Hoisting with let and const

// console.log(hoistedLet); // Error: Cannot access 'hoistedLet' before initialization
let hoistedLet = 'I am not hoisted';

Explanation

Variables declared with let and const are hoisted, but they are in a temporal dead zone until they are initialized. Attempting to access them before declaration results in an error.

Summary

JavaScript variables are essential building blocks for storing and manipulating data in programs. Understanding how to use var, let, and const, along with their scoping rules and initialization behavior, is crucial for writing effective JavaScript code.

Quick Reference

Keyword Scope Can Reassign Hoisting Must Initialize
var Function Yes Yes No
let Block Yes No No
const Block No No Yes

Best Practices

  • Use let for variables that will change.
  • Use const for variables that should not change (constants).
  • Avoid using var in modern JavaScript code to prevent scope-related issues.
  • Use meaningful variable names that describe the data they hold.

By mastering variables, you can manage and manipulate data effectively in your JavaScript applications!

You may also like