JS Basic Tutorial
In JavaScript, var
is one of the three ways to declare variables, along with let
and const
. Here's a detailed overview of how var
works and its characteristics:
var
:1) Function Scope:
Variables declared with var
are function-scoped. This means they are only accessible within the function in which they are defined. However, if declared outside a function, they become global variables.
Try it yourself
2) Re-declaration:
You can re-declare variables using var
within the same scope without any errors.
Try it yourself
3) Global Variables:
When a var
is declared outside any function, it becomes a property of the global object.
Try it yourself
4) No Block Scope:
var
does not respect block scope (i.e., { ... }
created by loops or conditionals). This means that variables declared with var
are accessible outside of blocks, even if they are declared inside.
Try it yourself