DEV Community

Angelika-Simonyan
Angelika-Simonyan

Posted on

JavaScript Variables

Variables are used to hold a value. It can hold any value, from primitives to objects. JavaScript supports five different types of variable.

Image description

4 Ways to Declare a JavaScript Variable:
Using var
Using let
Using const
Using nothing

Scope determines the accessibility (visibility) of variables.

JavaScript has 3 types of scope:
1)Block scope
2)Function scope
3)Global scope


Block Scope
Let and const provide Block Scope in JavaScript.
Variables declared inside a { } block cannot be accessed from outside the block:

Image description

Variables declared with the var keyword can NOT have block scope.
Variables declared inside a { } block can be accessed from outside the block.

Image description
--- --- --- --- --- ---
Variables declared within a JavaScript function, become LOCAL to the function.

Image description
--- --- --- --- --- ---

Function Scope
JavaScript has Function scope: Each function creates a new scope.

Variables defined inside a function are not accessible (visible) from outside the function.

Variables declared with var, let and const are quite similar when declared inside a function.

They all have Function Scope:

Image description

Image description

Image description

Global JavaScript Variables
A variable declared outside a function, becomes GLOBAL.
Image description
--- --- --- --- --- ---
Variables declared Globally (outside any function) have Global Scope.
Global variables can be accessed from anywhere in a JavaScript program.
Variables declared with var, let and const are quite similar when declared outside a block.
They all have Global Scope:
Image description
--- --- --- --- --- ---

The = sign in JavaScript isn't the same as the = sign in Math. In JavaScript, = means assignment.

Top comments (0)