JavaScript Variables with Examples
In JavaScript, a variable is a container that can hold a value or a reference to a value. Variables are used to store and manipulate data within a program.
There are three ways to declare a variable in JavaScript:
var: This is the original way to declare a variable in JavaScript. It is used to declare a variable that is function-scoped. That is, it can be accessed within the function in which it is declared, as well as any nested functions.
Example:
function myFunction() {
var x = 5;
console.log(x); // Output: 5
}
let: This is a relatively new way to declare a variable in JavaScript. It is used to declare a variable that is block-scoped. That is, it can be accessed only within the block in which it is declared (including any nested blocks).
Example:
function myFunction() {
if (true) {
let x = 5;
console.log(x); // Output: 5
}
console.log(x); // Output: ReferenceError: x is not defined
}
const: This is also a relatively new way to declare a variable in JavaScript. It is used to declare a variable that is block-scoped, like let. However, once a value is assigned to a const variable, it cannot be reassigned.
Example:
function myFunction() {
const x = 5;
x = 6; // Error: Assignment to constant variable.
}
It's important to note that variables in JavaScript are dynamically typed, meaning that the type of a variable can change at runtime based on the value assigned to it.