Do you understand variables : Let, Const and Ver in JavaScript? IF NO then let go π
Erasmus Kotoka
Posted on September 16, 2024
In JavaScript, variables are like containers that store data. There are three ways to create (or declare) these containers: var
, let
, and const
.
Letβs look at what makes them different! π
-
var
β The Old-School Way π
Scope: var
works within the function it's declared in (function-scoped), so it can be used anywhere inside that function. π
Hoisting: JavaScript "hoists" or moves var
declarations to the top of the function, but only the declaration, not the value.
This can sometimes cause confusion. π
Example:
var name = "Alice"; // Variable declared with 'var'
-
let
β The New Standard π±
Scope: let
is block-scoped, which means it's only available inside the block (curly braces {}
) where itβs declared.
This makes it more predictable. π§±
Reassignable: You can change the value of a let
variable if needed. π
Example:
let age = 25; // Variable declared with 'let'
age = 30; // You can reassign it
-
const
β The Permanent One π
Scope: Like
let
,const
is also block-scoped. βοΈNon-Reassignable: Once a value is assigned to a
const
variable, it can't be changed. This is used when you donβt want the value to change. β
Example:
const birthYear = 1995; // Variable declared with 'const'
birthYear = 2000; // Error! You can't change it
When to Use Them:
Use let
when you need to update the variableβs value later.
Use const
when the value should stay the same (like a constant).
Avoid var
in modern JavaScript because let
and const
are more reliable.
By understanding let
, const
, and var
, you'll write cleaner, more predictable JavaScript! π―
COdeWith #KOToka
KEEPCOding
DOntGIVeUP
Posted on September 16, 2024
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.