Javascript Variables
What is Variable in Javascript:
You can declare variables using the keywords var, let, or const in JavaScript, and these keywords denote different scopes.
var:
- The oldest way to declare variables.
- The behavior is either function-scoped or not block-scoped, so it can be globally-scoped as well.
- It can be redeclared and updated.
var message = "Hello, World!";
var count = 10;
// It can be updated
count = count + 5;
// It can be redeclared
var message = "New message";
let:
- Introduced in ECMAScript 6 (ES6).
- It has block-scoped behavior.
- It is not possible to either replace or redeclare the same in the same scope.
let name = "John";
let age = 25;
// It can be updated
age = age + 1;
// It cannot be redeclared in the same scope
// let name = "Jane"; // This would throw an error
const:
- Also introduced in ECMAScript 6 (ES6).
- It has block-scoped behavior.
- It cannot be updated or redeclared.
const pi = 3.14;
const language = "JavaScript";
// Cannot be updated
// pi = 3.14159; // This would throw an error
// Cannot be redeclared in the same scope
// const pi = 3.14159; // This would throw an error
As a rule, you should always adopt a let over a const, if the latter does not require rare reassignments.
In order to use the function again and prevent the accidental reassignment of the variable, the function automatically provides this feature.