What is a Variable?
In JavaScript, a variable is a container for storing data values.
Variables allow programmers to label data with a descriptive name, so
the program can be understood more clearly by the reader and
maintained more easily. JavaScript uses the keywords var,
let, and const for variable declarations,
each serving different purposes and scopes.
-
vardeclares a variable optionally initializing it to a value. Variables declared withvarare scoped to the function within which they are declared, or globally if declared outside any function.varvariables can be re-declared and updated. -
letallows you to declare variables that are limited in scope to the block, statement, or expression in which they are used. This is unlike thevarkeyword, which defines a variable globally, or locally to an entire function regardless of block scope. Variables declared withletcan be updated but not re-declared within the same scope. -
constis used to declare variables whose values are never intended to change.constdeclarations share some similarities withletdeclarations in that the variable is blocked-scoped. However, a variable declared withconstmust be initialized at the time of declaration, and its value cannot be re-assigned.
These distinctions are crucial for writing clear, effective code and
understanding how variables behave differently depending on their
declaration context in JavaScript. Understanding the scope and
mutability of variables declared with var,
let, and const can help prevent bugs and aid
in maintaining code.
Practical Examples
Using var
var greeting = 'Hello World!';
console.log(greeting); // Outputs: Hello World!
// Re-declaring and updating var
var greeting = 'Hello again!';
console.log(greeting); // Outputs: Hello again!
Using let
let counter = 1;
counter = 2; // Updating let variable
console.log(counter); // Outputs: 2
// let cannot be re-declared in the same scope
// let counter = 3; // This would cause an error
Using const
const pi = 3.14;
console.log(pi); // Outputs: 3.14
// const must be initialized and cannot be re-assigned
// pi = 1.59; // This would cause an error
These examples show the typical use cases for var,
let, and const in JavaScript, highlighting
the importance of choosing the right type of variable based on the
needs of your code.
Try it Yourself
Type your own greeting message and see it displayed below:
Test Your Knowledge: JavaScript Variables
Which keyword declares a variable that cannot be reassigned?