In Javascript, variables are used to store and manipulate data.
Variables are containers for values and are declared using keywords like let, const, or var.
Variable names can include letters, numbers, underscores `_`, and dollar signs `$`.
"Variable names" cannot start with a number.
Javascript is case-sensitive, so yourVariableName and yourvariablename will treated as different variables.
The `let` variable was introduced in ES6 (ECMAScript 2015) to address some issues with the `var` variable.
`let` variables have blocked-scope. They can be accessible within the same block of code.
Use the `let` keyword to declare a variable that can be reassigned.
The `let` variable can't be re-declared in the same block scope.
let name = 'Alice'; let age = 20;
The `const` variable was introduced in ES6 (ECMAScript 2015) to address some issues with the `var` variable.
`const` variables have blocked-scope. They can be accessible within the same block of code.
Use const to declare a `constant` variable whose value cannot be reassigned:
The `const` variables can't be re-declared in the same block scope.
function constBlockScope() { const isStudent = true; // with `const` re-declare or reassign variable won't work // const isStudent = false; if (isStudent) { const isTopper = false; console.log(isStudent); // Output: true } // through error becoz const has block-scoped // console.log(isTopper); // Output: false } constBlockScope();
The var keyword was originally used to create variables in Javascript before the introduction of `let` and `const`, but now it is considered outdated. It has some differences in scoping behaviour compared to let and const.
`var` variables have functional-scoped.
If we declare a `var` variable outside of any function, the variable becomes a global variable, which can lead to unintended consequences and potential issues with variable hoisting.
function varFunctionalScope() { var isStudent = true; // with `var` keyword we can re-declare same variable in function or block scope // var isStudent = true; if (isStudent) { var isTopper = false; console.log(isStudent); // Output: true } console.log(isTopper); // Output: false // if we re-declare `var` variable in code it won't through error. isStudent = false } varFunctionalScope(); // if we un-comment this line we will encounter an error // console.log(isStudent); // Error: `isStudent` is not defined
Note: `var` variables are visible throughout the function in which they are declared.