JS Basic Tutorial
In JavaScript, variables are used to store data values. They act as containers to hold values like numbers, strings, objects, etc.
You can declare JavaScript variables using:
var
(old way, avoid using in modern code)let
(block-scoped, preferred for variable values that change)const
(block-scoped, preferred for constants or values that won't change)_
, or $
.myVar
is different from MyVar
).var
, let
, const
).
Keyword |
Scope |
Can Reassign? |
Can Redeclare? |
Hoisting |
---|---|---|---|---|
var |
Function Scope |
Yes |
Yes |
Hoisted with |
let |
Block Scope |
Yes |
No |
Hoisted without initialization |
const |
Block Scope |
No |
No |
Hoisted without initialization |
Try it yourself
var
inside a function are function-scoped.let
and const
inside a block {}
are block-scoped.Try it yourself
var
are hoisted to the top of their scope and initialized with undefined
.let
and const
are hoisted but not initialized.const
by default.let
if the variable needs to change.var
unless absolutely necessary.userAge
, totalPrice
).firstName
, lastValue
).JavaScript variables can store values of different data types:
"Hello"
42
true
/ false
null
undefined
{ key: "value" }
[1, 2, 3]
function() {}
const
)