In JavaScript, variables are used to store data values. They act as containers for storing information that can be referenced and manipulated throughout a program. Variables in JavaScript are declared using keywords such as var, let, or const.
Declaration of Variables:
-
var (ES5):
- Declares a variable that is function-scoped.
var myVar = 'Hello';
-
let (ES6+):
- Declares a block-scoped variable that can be reassigned.
let age = 25; age = 30; // Can be reassigned
-
const (ES6+):
- Declares a block-scoped variable that cannot be reassigned. However, for objects and arrays, their properties and elements can be modified.
const pi = 3.14;
Characteristics of Variables:
-
Naming Rules:
- Variable names in JavaScript must begin with a letter (a-z, A-Z), underscore (_), or dollar sign ($) and can contain letters, digits, underscores, or dollar signs.
- They cannot use reserved keywords.
-
Data Types:
- Variables in JavaScript can hold different types of data: numbers, strings, booleans, objects, arrays, functions, etc.
-
Scope:
-
var
has function-level scope, whilelet and const
have block-level scope (inside curly braces{}
).
-
-
Hoisting:
-
var
variables are hoisted (moved to the top of their scope) and initialized withundefined
before the code is executed. -
let and const
are also hoisted but not initialized, resulting in a "Temporal Dead Zone" where accessing them before declaration causes a ReferenceError.
-
Example Usage:
// Variable declarations
var name = 'Alice';
let age = 30;
const PI = 3.14;
// Usage
console.log(name); // Output: Alice
age = 35; // Reassigned value
console.log(age); // Output: 35
// Constants cannot be reassigned
// PI = 3; // This would throw an error
// Data types in variables
let isStudent = true;
let scores = [90, 85, 78];
let person = { firstName: 'Bob', lastName: 'Smith' };
Variables in JavaScript are fundamental for storing and manipulating data, and their behavior differs based on their declaration (var, let, const
) and scope within the code.