Skip to main content

JavaScript Variables

Variables are one of the most fundamental concepts in any programming language. In JavaScript, variables act as containers that store data values, allowing you to work with and manipulate data throughout your program.

What are Variables?

Think of variables as labeled boxes where you can store information. Each variable has:

  • A name (identifier)
  • A value (the data it holds)
  • A type (determined by the value it contains)

Declaring Variables in JavaScript

JavaScript provides three ways to declare variables:

1. Using let

let is the modern way to declare variables that can be reassigned later.

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

age = 26; // Reassigning the value
console.log(age); // Output: 26

2. Using const

const declares constants - variables whose values cannot be changed after initialization.

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

// Trying to reassign will cause an error
// PI = 3.14; // TypeError: Assignment to constant variable

3. Using var (older method)

var is the original way to declare variables in JavaScript, but it has some scoping issues that let and const were designed to solve.

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

var name = "Jane"; // var allows redeclaration
console.log(name); // Output: Jane

Variable Naming Rules

When naming variables in JavaScript, follow these rules:

  1. Names can contain letters, digits, underscores, and dollar signs
  2. Names must begin with a letter, $ or _
  3. Names are case sensitive (myVar and myvar are different variables)
  4. Reserved words (like JavaScript keywords) cannot be used as names
javascript
// Valid variable names
let firstName = "John";
let $price = 19.99;
let _count = 5;
let camelCaseVariable = true;

// Invalid variable names
// let 2ndPlace = "Silver"; // Cannot start with a digit
// let function = "Something"; // Cannot use a reserved word

Variable Data Types

JavaScript variables can hold different types of data:

Primitive Data Types

  1. String: Text values
javascript
let greeting = "Hello, world!";
let message = 'Welcome to JavaScript';
  1. Number: Numeric values (integers and floating-point)
javascript
let integer = 42;
let decimal = 3.14;
  1. Boolean: true or false values
javascript
let isLoggedIn = true;
let hasPermission = false;
  1. Undefined: A variable declared without a value
javascript
let empty;
console.log(empty); // Output: undefined
  1. Null: Represents the intentional absence of any value
javascript
let noValue = null;
  1. Symbol: Unique and immutable primitive values (ES6)
javascript
let uniqueId = Symbol('id');
  1. BigInt: For large integers (ES2020)
javascript
let bigNumber = 1234567890123456789012345678901234567890n;

Reference Data Types

  1. Object: Collection of key-value pairs
javascript
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};

console.log(person.firstName); // Output: John
  1. Array: Ordered list of values
javascript
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: red
  1. Function: Reusable blocks of code
javascript
let greet = function() {
return "Hello!";
};

console.log(greet()); // Output: Hello!

Variable Scope

Scope determines where variables are accessible in your code.

Block Scope

Variables declared with let and const have block scope - they're only accessible within the block they're declared in.

javascript
if (true) {
let blockScoped = "I'm only available in this block";
console.log(blockScoped); // Output: I'm only available in this block
}

// console.log(blockScoped); // ReferenceError: blockScoped is not defined

Function Scope

Variables declared with var have function scope - they're accessible anywhere within the function they're declared in.

javascript
function showExample() {
var functionScoped = "I'm available throughout the function";

if (true) {
var alsoFunctionScoped = "I'm also available throughout the function";
}

console.log(functionScoped); // Output: I'm available throughout the function
console.log(alsoFunctionScoped); // Output: I'm also available throughout the function
}

showExample();
// console.log(functionScoped); // ReferenceError: functionScoped is not defined

Global Scope

Variables declared outside any function or block have global scope - they're accessible anywhere in your code.

javascript
let globalVariable = "I'm available everywhere";

function checkScope() {
console.log(globalVariable); // Output: I'm available everywhere
}

checkScope();
console.log(globalVariable); // Output: I'm available everywhere

Real-World Examples

Example 1: Shopping Cart

javascript
// Shopping cart item variables
const productId = "p123";
let quantity = 2;
let price = 19.99;
let isDiscounted = true;

// Calculate total
let total = quantity * price;
console.log(`Cart total: $${total}`); // Output: Cart total: $39.98

// Apply discount
if (isDiscounted) {
const discountRate = 0.1; // 10% discount
total = total * (1 - discountRate);
}

console.log(`Final price: $${total.toFixed(2)}`); // Output: Final price: $35.98

Example 2: User Profile

javascript
// User profile information
const userId = "user_789"; // This won't change
let username = "codemaster"; // This might change if user updates profile
let loginCount = 5;
let isActive = true;

// User logs in again
loginCount = loginCount + 1;

// Display user information
console.log(`User: ${username} (ID: ${userId})`);
console.log(`Login count: ${loginCount}`);
console.log(`Account active: ${isActive ? "Yes" : "No"}`);

/* Output:
User: codemaster (ID: user_789)
Login count: 6
Account active: Yes
*/

Best Practices for Using Variables

  1. Use descriptive names that explain what the variable contains

    javascript
    // Bad
    let x = 5;

    // Good
    let numberOfStudents = 5;
  2. Use const by default and only use let when you need to reassign values

    javascript
    const API_URL = "https://api.example.com";  // Will never change
    let currentScore = 0; // Will change during the game
  3. Declare variables at the top of their scope for better readability

    javascript
    function calculateTotal() {
    // Declare variables at the top
    const taxRate = 0.07;
    let subtotal = 0;
    let items = getCartItems();

    // Rest of the function...
    }
  4. Avoid global variables when possible to prevent naming conflicts

    javascript
    // Instead of global variables
    function processCart() {
    // Localized variables
    const taxRate = 0.07;
    let cartTotal = 0;
    // ...
    }

Summary

JavaScript variables are essential for storing and working with data in your programs. They come in three declaration types (var, let, and const), can hold various data types, and follow specific scope rules.

Understanding variables is fundamental to JavaScript programming, as they're used in virtually every aspect of your code - from storing user input to calculating values and controlling application flow.

Exercises

  1. Create variables to store your name, age, and favorite programming language using the appropriate declaration keywords.
  2. Create a simple calculator that stores two numbers in variables and performs addition, subtraction, multiplication, and division.
  3. Create an object representing a book with properties for title, author, and publication year.
  4. Write a function that takes a person's first and last name as variables and returns a full name.
  5. Experiment with variable scope by creating variables in different blocks and trying to access them outside those blocks.

Additional Resources



If you spot any mistakes on this website, please let me know at [email protected]. I’d greatly appreciate your feedback! :)