Variables are fundamental building blocks in any programming language, and JavaScript is no exception. They act as containers for storing data values. In this post, we'll explore how variables work in JavaScript, including the different ways to declare them and the various data types they can hold.
Variables allow us to:
In modern JavaScript, there are three primary keywords used to declare variables:
var
The oldest way to declare variables. It has function scope and can be re-declared and updated.
var greeting = "Hello!";
let
Introduced in ES6, let
declares variables that are block-scoped and can be updated but not re-declared within the same scope.
let count = 0;
const
Also introduced in ES6, const
declares variables whose values cannot be reassigned. They must be initialized at the time of declaration and are also block-scoped.
const PI = 3.14159;
JavaScript is a dynamically-typed language, meaning you don't need to declare the type of a variable explicitly. The interpreter infers the type based on the value assigned.
These are immutable data types:
"Hello World"
10
, 10.5
true
or false
.Here's a simple example demonstrating variable declaration and usage:
let userName = "Alice";
let age = 30;
const isStudent = false;
// Accessing and displaying variables
console.log("User: " + userName);
console.log("Age: " + age);
console.log("Is student? " + isStudent);
// Modifying a 'let' variable
age = age + 1;
console.log("Next year's age: " + age);
// Attempting to modify a 'const' variable (will cause an error)
// PI = 3.14; // TypeError: Assignment to constant variable.
const
by default, and use let
only when you know the variable's value will need to change.var
in new code due to its hoisting and scope complexities.