All About Javascript Variables
Variable Types
var const let
Var
The var keyword is used to declare variables in JavaScript.
Variables declared with var are function-scoped. This means
they are accessible within the function in which they are
declared, but not outside of it.
Variables declared with var are hoisted to the top of their
containing function or global scope. This means you can use a
variable before it's declared, but its value might be undefined
until it's assigned a value.
Unlike let and const, var does not have block scope. Variables
declared with var inside a block (like within an if statement or
loop) are still accessible outside of that block.
Due to its hoisting and lack of block scope, using var can
sometimes lead to hard-to-debug issues. As of ES6, it's generally
recommended to use let and const instead for better scoping
and predictable behavior.
const
The const keyword is used to declare constants in JavaScript.
Once a value is assigned to a const variable, it cannot be
reassigned or changed. The value remains constant throughout
the scope of the variable.
Variables declared with const are block-scoped. They are only
accessible within the block (a pair of curly braces) in which they
are declared.
Like variables declared with let, const variables are also hoisted
to the top of their containing block. However, if you try to
access a const variable before its declaration, you'll get a
ReferenceError.
When you declare a const variable, you must immediately
initialize it with a value. Unlike var, const doesn't allow
uninitialized declarations.
It's recommended to use const by default for variables that
don't need to be reassigned. This can improve code readability
and prevent accidental changes to values.
let
Variables declared with let are block-scoped, meaning they are
accessible only within the block (a pair of curly braces) in which
they are declared.
Unlike variables declared with var, let variables are not hoisted
to the top of their containing scope. If you try to access a let
variable before its declaration, you'll get a ReferenceError.
Variables declared with let can be reassigned with a new value
after their initial declaration.
You cannot redeclare a variable using let within the same block
scope. Attempting to do so will result in a syntax error.
If a let variable is declared within a function, it's accessible only
within that function.
Since let provides block-scoping and avoids hoisting-related
problems, it's generally recommended over using var for most
use cases in modern JavaScript.