JavaScript Variables
What are Variables?
Variables are containers for storing data values. In JavaScript, you can declare variables using var, let, or const.
Declaring Variables
Using var (Legacy)
Example
var name = "John";
var age = 25;
Using let (Modern)
Example
let name = "John";
let age = 25;
Using const (Constants)
Example
const PI = 3.14159;
const company = "The World of Computing According to Dave";
Variable Naming Rules
- Variable names can contain letters, digits, underscores, and dollar signs
- Must begin with a letter, underscore, or dollar sign
- Are case-sensitive (age and Age are different)
- Cannot use reserved words (if, else, for, etc.)
- Use camelCase for multi-word variables
Assigning Values
You can assign values to variables when you declare them, or later:
Example
// Declare and assign
let x = 5;
// Declare first
let y;
y = 10;
// Multiple variables
let a = 1, b = 2, c = 3;
Variable Types
JavaScript variables can hold different types of data:
Example
let name = "John"; // String
let age = 25; // Number
let isStudent = true; // Boolean
let hobbies = ["reading", "coding"]; // Array
let person = {name: "John", age: 25}; // Object
let vs const vs var
| Keyword | Scope | Reassignable |
|---|---|---|
var |
Function scope | Yes |
let |
Block scope | Yes |
const |
Block scope | No |
Best Practices
- Use
constby default,letwhen you need to reassign - Avoid using
varin modern JavaScript - Use meaningful variable names
- Initialize variables when declaring them
- Use camelCase for variable names