Variable
- A variable is a named container used to store data Values.
- It is used for storing, retrieving, and manipulating data during program execution.
Rules for Naming Variables
- A variable name can contain letters, digits, _ (underscore), and $ (dollar sign).
- A variable name cannot start with a number.
- Variable names are case-sensitive(Age and age).
- We cannot use JavaScript reserved keywords as variable names. Example: var, let, const, if, for, etc.
- Use meaningful names that describe the stored data. Example: studentName is better than x.
Types of Variables in JavaScript
- var
- let
- const
Variable Declaration
- Declaration means creating a variable by specifying its name using var, let, or const.
let age;
Variable Initialization
- Initialization means assigning a value to a variable for the first time.
let age = 22;
Variable Reassignment
- Reassignment means changing the existing value of a variable.
let age = 22;
age = 23;
var
- var is a keyword used to declare a variable in JavaScript.
- It is the older way of declaring variables.
- A variable declared using var can be redeclared and reassigned.
- It is function-scoped, which means it is accessible throughout the function in which it is declared.
function student() {
var name = "Laksh"; // Declaration + Initialization
name = "Lakshmi"; // Reassignment
var name = "Arun"; // Redeclaration
console.log(name); // Arun
}
console.log(name); // Error
let
- A variable declared using let can be reassigned, but it cannot be redeclared in the same scope.
- It is block-scoped, which means it can be accessed only within the block { } where it is declared.
- It was introduced in ES6 to overcome some limitations of var.
function student() {
let name = "John"; // Declaration + Initialization
name = "David"; // Reassignment
let name = "Max"; // Error
{
let name = "Alex"; // New variable in another block
console.log(name); // Alex
}
console.log(name); // David
}
student();
const
- A variable declared using const cannot be redeclared or reassigned in the same scope.
- It is also block-scoped and It is used when the value of a variable should not be changed after initialization.
function student() {
const name = "John";
{
const name = "David";
console.log(name); // David
}
console.log(name); // John
}
Top comments (0)