Section 2.1: Syntax and Basics
Tutorial 2.1.2: Variables and Constants
Variables and Constants in JavaScript
In JavaScript, variables and constants are used to store data that your program can use and manipulate. This tutorial explains how to declare, initialize, and use variables and constants effectively.
Declaring Variables
Variables in JavaScript can be declared using three keywords: var, let, and const.
var(Legacy):
- Used in older JavaScript versions but largely replaced by
letandconst. - Example:
var message = "Hello, World!";
console.log(message);let(Modern):
- Preferred for declaring variables that can change value.
- Example:
let age = 25;
age = 26; // Allowed
console.log(age); // 26const(Constants):
- Used for variables whose value should not change.
- Example:
const PI = 3.14;
console.log(PI); // 3.14Rules for Naming Variables
- Must start with a letter, underscore (
_), or dollar sign ($).
- Valid:
name,_age,$price - Invalid:
1name,@value
- Case-sensitive:
ageandAgeare different.
- Avoid JavaScript reserved keywords (e.g.,
let,const,var).
Variable Initialization
Variables can be declared without assigning a value. Uninitialized variables are undefined.
Example:
let greeting;
console.log(greeting); // undefinedUsing let and const in Practice
- When to Use
let:
- Use
letfor variables whose value may change. - Example:
let score = 10;
score += 5; // score is now 15- When to Use
const:
- Use
constfor constants or variables that should remain unchanged. - Example:
const API_KEY = "12345";
// API_KEY = "67890"; // Error: Assignment to constant variableScope of Variables
- Block Scope (
letandconst):
- Variables are accessible only within the block they are declared in.
- Example:
{
let x = 10;
console.log(x); // 10
}
console.log(x); // Error: x is not defined- Function Scope (
var):
- Variables are accessible within the entire function they are declared in.
- Example:
function test() {
var y = 20;
console.log(y); // 20
}
console.log(y); // Error: y is not definedBest Practices
- Use
constby default; switch toletif the value needs to change. - Avoid using
varin modern JavaScript. - Use meaningful names for variables.
Exercise
- Declare a variable
nameusingletand assign it your name. Log it to the console. - Declare a constant
BIRTH_YEARwith your birth year. Try to change its value and note the error.
Example:
let name = "Alice";
console.log(name);
const BIRTH_YEAR = 1990;
// BIRTH_YEAR = 2000; // Error: Assignment to constant variable