JavaScript Variables

Variables are fundamental building blocks in JavaScript. They are containers for storing data values. Think of them as labeled boxes where you can put different types of information.

Declaring Variables

You can declare variables in JavaScript using three keywords:

Declaration Examples

Using let:

let message;
message = "Hello, World!";
console.log(message); // Output: Hello, World!

Using const:

const pi = 3.14159;
console.log(pi); // Output: 3.14159
// pi = 3.14; // This would cause an error

Using var (generally avoid in modern JS):

var count = 10;
console.log(count); // Output: 10

Variable Naming Rules

Valid and Invalid Names

Valid Names:

Invalid Names:

Data Types

JavaScript has several primitive data types:

JavaScript also has a non-primitive data type:

Data Type Examples

let greeting = "Hello there!";
let age = 30;
let isStudent = false;
let x; // x is undefined
let person = { firstName: "John", lastName: "Doe" };

The typeof Operator

The typeof operator can be used to find the type of a variable:

let name = "Alice";
console.log(typeof name); // Output: string

let score = 95;
console.log(typeof score); // Output: number

let isActive = true;
console.log(typeof isActive); // Output: boolean

let data;
console.log(typeof data); // Output: undefined

console.log(typeof null); // Output: object (This is a known quirk in JavaScript)

Best Practices