Understand how variables store and manage data in JavaScript, including declaration keywords, scope, and best practices.
var
, let
, or
const
, each with different scoping and mutability rules.
Understanding how variables behave in different scopes is key to
writing effective JavaScript code.
This example shows variable declaration and scope:
// var: function scoped, can be redeclared and updated
var x = 10;
var x = 20; // redeclaration allowed
x = 30; // update allowed
// let: block scoped, cannot be redeclared, can be updated
let y = 15;
// let y = 25; // Error: redeclaration not allowed
y = 35; // update allowed
// const: block scoped, cannot be redeclared or updated
const z = 50;
// z = 60; // Error: assignment to constant variable
console.log(x, y, z);
Key takeaways:
var
has function scope and allows redeclaration.let
and const
have block scope.const
variables must be initialized and cannot be reassigned.const
to protect important
values from accidental reassignment.
Q1: Which keyword is block scoped?
Answer: B. let
Q2: What happens if you redeclare a var
variable?
Answer: C. It overwrites the previous variable
Q3: Can a const
variable be reassigned?
Answer: B. No
Q4: Which variable declaration keyword should be used for constants?
Answer: C. const