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.
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.
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.
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:
- Names can contain letters, digits, underscores, and dollar signs
- Names must begin with a letter, $ or _
- Names are case sensitive (
myVar
andmyvar
are different variables) - Reserved words (like JavaScript keywords) cannot be used as names
// 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
- String: Text values
let greeting = "Hello, world!";
let message = 'Welcome to JavaScript';
- Number: Numeric values (integers and floating-point)
let integer = 42;
let decimal = 3.14;
- Boolean: true or false values
let isLoggedIn = true;
let hasPermission = false;
- Undefined: A variable declared without a value
let empty;
console.log(empty); // Output: undefined
- Null: Represents the intentional absence of any value
let noValue = null;
- Symbol: Unique and immutable primitive values (ES6)
let uniqueId = Symbol('id');
- BigInt: For large integers (ES2020)
let bigNumber = 1234567890123456789012345678901234567890n;
Reference Data Types
- Object: Collection of key-value pairs
let person = {
firstName: "John",
lastName: "Doe",
age: 30
};
console.log(person.firstName); // Output: John
- Array: Ordered list of values
let colors = ["red", "green", "blue"];
console.log(colors[0]); // Output: red
- Function: Reusable blocks of code
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.
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.
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.
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
// 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
// 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
-
Use descriptive names that explain what the variable contains
javascript// Bad
let x = 5;
// Good
let numberOfStudents = 5; -
Use
const
by default and only uselet
when you need to reassign valuesjavascriptconst API_URL = "https://api.example.com"; // Will never change
let currentScore = 0; // Will change during the game -
Declare variables at the top of their scope for better readability
javascriptfunction calculateTotal() {
// Declare variables at the top
const taxRate = 0.07;
let subtotal = 0;
let items = getCartItems();
// Rest of the function...
} -
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
- Create variables to store your name, age, and favorite programming language using the appropriate declaration keywords.
- Create a simple calculator that stores two numbers in variables and performs addition, subtraction, multiplication, and division.
- Create an object representing a book with properties for title, author, and publication year.
- Write a function that takes a person's first and last name as variables and returns a full name.
- 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! :)