In JavaScript a variable can be defined using the keywords var
, let
, or const
.
Before we can understand how var
, let
, and const
differ, we need to understand a computer science-y concept called scope.
Scope essentially means where these variables are available for use.
Global Scope
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Function Scope
Variables declared Locally (inside a function) have Function Scope.
Local variables can only be accessed from inside the function where they are declared.
Block Scope
A block of code is the code between curly braces in JavaScript.
Variables declared inside a block {} have block scope.
Variables declared with the var keyword cannot have Block Scope.
var
var
declarations are globally scoped or function/locally scoped.
The scope is global when a var
variable is declared outside a function.
var is function scoped when it is declared within a function.
variables declared with var
keyword can be re-declared like this
or their value can be updated like this
let
let
is now preferred for variable declaration. It's no surprise as it comes as an improvement to var
declarations. It also solves the problem with var
. Let's consider why this is so.
let
is block-scoped, so a variable declared in a block with let
is only available for use within that block.
variables declared with let
keyword cannot be re-declared it will throw error like this
let
variables can be updated within its scope like this
const
Variables declared with the const
maintain constant values. const
declarations share some similarities with let
declarations.
Like let declarations, const
declarations can only be accessed within the block they were declared.
But variable declared with const
can neither be re-declared nor re-assigned
Thanks for reading.
"Don't miss out" Follow my Social handles👉
Subscribe my YouTube channel😊
Instagram😊 || Twitter😊
If you find this helpful and want to support💲 Buy Me Coffee☕
Top comments (2)
Variables can also be declared without using
let
,var
, orconst
if you're not in strict mode - although in most situations this is not really best practice. Defining a function using thefunction
keyword also technically defines a variable - with a function as its valueBeautifully explained in lay terms. Important read for those new to and learning JavaScript.