JavaScript variables are containers for storing data values.
You can declare a variable using the var
, let
, or const
keywords. var
is function-scoped and has been traditionally used, but its scope can lead to unexpected behavior.
let
and const
are block-scoped, providing better control over the variable's scope.
let
allows for reassignment, while const
is used for values that should not be reassigned.
Variables can store various data types such as numbers, strings, objects, arrays, and functions.
JavaScript is dynamically typed, meaning the type of a variable is determined at runtime and can change as the program executes.
Properly naming variables is crucial for code readability and maintenance.
Use descriptive names that clearly indicate the variable’s purpose.
Examples
Number Variable:
let age = 25;
Explanation: This declares a variable
age
and assigns it the numeric value 25.String Variable:
const name = "Alice";
Explanation: This declares a constant variable
name
and assigns it the string "Alice".Boolean Variable:
var isStudent = true;
Explanation: This declares a variable
isStudent
and assigns it the boolean valuetrue
.Array Variable:
let fruits = ["apple", "banana", "cherry"];
Explanation: This declares a variable
fruits
and assigns it an array containing three strings.Object Variable:
const person = { firstName: "John", lastName: "Doe" };
Explanation: This declares a constant variable
person
and assigns it an object with two properties.Undefined Variable:
let x;
Explanation: This declares a variable
x
without assigning a value, so it isundefined
.Null Variable:
let y = null;
Explanation: This declares a variable
y
and assigns it the valuenull
, indicating the absence of any object value.Function Variable:
const greet = function() { return "Hello"; };
Explanation: This declares a constant variable
greet
and assigns it an anonymous function that returns the string "Hello".Variable Reassignment:
let count = 10; count = 20;
Explanation: This declares a variable
count
and assigns it the value 10, then reassigns it to 20.Template Literals:
const greeting = `Hello, ${name}`;
Explanation: This declares a constant variable
greeting
and uses template literals to include the value ofname
within the string.
These examples illustrate the flexibility and dynamism of JavaScript variables, highlighting their essential role in storing and manipulating data within programs.