Skip to content

JavaScript Variables

JavaScript variables are named containers for storing data values. Think of them as labels for information your program needs to remember and work with.

In this example, x, y, and sum are variables:

const x = 5;
const y = 6;
const sum = x + y; // sum will store the value 11

From the example above:

  • x stores the value 5.
  • y stores the value 6.
  • sum stores the result of x + y, which is 11.

In modern JavaScript (ES6 and later), variables are typically declared using let and const. The older keyword var also exists but has different scoping rules and is generally avoided in new code.

  • let: Declares a block-scoped variable. The value of a let variable can be reassigned.
  • const: Declares a block-scoped constant. Its value cannot be reassigned after initialization. For objects and arrays, const means the reference to the object/array cannot change, but the contents of the object/array can still be modified.
  • var: Declares a function-scoped or globally-scoped variable (older syntax). It can be reassigned and re-declared.

Creating (declaring) a variable in JavaScript:

let carName; // Declares a variable named carName (value is undefined initially)
carName = "Volvo"; // Assigns the string "Volvo" to carName
const year = 2024; // Declares a constant and initializes it
// year = 2025; // This would cause an error because 'year' is a constant

It’s good practice to declare variables before they are used and initialize const variables at the time of declaration.

Scope determines the accessibility (visibility) of variables.

  • Block Scope (let and const): Variables declared with let and const are only accessible within the block of code (defined by {...}) where they are declared. This includes loops, if statements, and function blocks.
  • Function Scope (var): Variables declared with var are accessible throughout the function in which they are declared, regardless of block structure.
  • Global Scope: Variables declared outside any function or block are global and accessible from anywhere in your script.

Example of block scope:

function testScope() {
if (true) {
let blockScopedVar = "I am block-scoped";
const blockScopedConst = "Me too!";
var functionScopedVar = "I am function-scoped";
console.log(blockScopedVar); // Accessible
}
// console.log(blockScopedVar); // Error: blockScopedVar is not defined here
// console.log(blockScopedConst); // Error: blockScopedConst is not defined here
console.log(functionScopedVar); // Accessible
}
testScope();

Using let and const helps prevent bugs related to variable hoisting and unintended global variables that were common with var.

All JavaScript variables must be identified with unique names, called identifiers.

Rules for constructing variable names:

  • Names can contain letters, digits, underscores (_), and dollar signs ($).
  • Names must begin with a letter, a dollar sign ($), or an underscore (_). (Conventionally, start with a letter).
  • Names are case sensitive (myVariable and myvariable are different).
  • Reserved keywords (like let, const, function, if) cannot be used as variable names.

Use descriptive and meaningful names (e.g., userName, totalAmount) to make your code more readable. CamelCase (userName) is the standard convention.

In JavaScript, the equal sign (=) is an assignment operator, not an “equal to” operator (for equality, use == or ===).

It assigns the value on its right to the variable on its left.

let x = 10; // Assigns 10 to x
x = x + 5; // Assigns the value of (x + 5) back to x. Now x is 15.

JavaScript variables can hold different types of data:

  • String: Textual data, e.g., "Hello", 'JavaScript'. (Enclosed in quotes or backticks).
  • Number: Numeric data, e.g., 100, 3.14, 2.5e5 (scientific notation). JavaScript has one number type for both integers and floating-point numbers.
  • Boolean: Logical values, true or false.
  • Object: A collection of key-value pairs, e.g., { name: "John", age: 30 }. Arrays and Functions are also types of objects.
  • Array: An ordered list of values, e.g., [1, 2, "apple"].
  • null: Represents the intentional absence of any object value.
  • undefined: Indicates that a variable has been declared but not yet assigned a value.
  • Symbol (ES6): A unique and immutable primitive value, often used as object property keys.
  • BigInt (ES2020): For integers of arbitrary length.

JavaScript is dynamically typed, meaning you don’t have to declare the type of a variable. The type is determined automatically at runtime.

let pi = 3.14; // pi is a Number
let person = "John Doe"; // person is a String
let isHappy = true; // isHappy is a Boolean

You can declare multiple variables in one statement, separated by commas. However, it’s often clearer to declare each variable on its own line.

// Common way:
let name = "John Doe";
let age = 30;
let city = "New York";
// Also possible (less common for `let` and `const` due to block scoping benefits of separate lines):
let user = "Jane", role = "Admin", experience = 5;

A variable declared without an assigned value will have the value undefined.

let country;
console.log(country); // Output: undefined

let and const: Variables declared with let or const cannot be re-declared within the same scope. Doing so will result in a SyntaxError.

let myVar = "initial";
// let myVar = "new"; // Error: Identifier 'myVar' has already been declared
const myConst = 10;
// const myConst = 20; // Error: Identifier 'myConst' has already been declared

var (Older Syntax): Variables declared with var can be re-declared in the same scope without error. The re-declaration is effectively ignored if it doesn’t also assign a new value; if it does, the variable takes the new value.

var oldVar = "Volvo";
var oldVar; // No error, oldVar is still "Volvo"
console.log(oldVar); // Output: "Volvo"
var oldVar = "Saab"; // Re-assignment along with re-declaration
console.log(oldVar); // Output: "Saab"

This re-declaration behavior of var can lead to bugs, which is one reason let and const are preferred.

You can perform arithmetic operations with JavaScript variables using operators like +, -, *, /.

const x = 5 + 2 + 3; // x will be 10

JavaScript performs type coercion when operators are used with mixed types. The + operator is special: it performs addition for numbers and concatenation for strings.

const strNum = "5" + 2 + 3; // Result: "523" (String concatenation)
const numStr = 2 + 3 + "5"; // Result: "55" (Addition then concatenation)
console.log("The year is " + 2024); // Result: "The year is 2024"
If you use the + operator and one of the operands is a string, JavaScript will convert the other operand(s) to strings and perform concatenation. Be mindful of this behavior.