A variable is something that can store a value—like a container—and that value can change over time.
How to Declare a Variable
In JavaScript, you can declare variables using three keywords:
-
var
-
let
-
const
Let’s break down what each one does:
-
var
was the original way to declare variables in JavaScript. However, it can be confusing and may cause bugs due to its function-level scope. -
let
is the modern and preferred way. It fixes many issues caused byvar
, offering better scoping and clearer behavior. -
const
is used when you want to declare a variable whose value won’t change.
In this guide, we’ll mostly use let
for declaring variables.
Declaring a Variable
To declare a variable using let
, just write the keyword followed by the variable name:
In the example above, msg
is declared but not assigned a value. Its default value is undefined
.
Assigning a Value
You can assign a value to a variable when you declare it or afterward:
Or you can do both at the same time:
Declaring Multiple Variables
You can also declare and initialize multiple variables in one line:
Or even write them across multiple lines for better readability:
Copying Values Between Variables
You can copy the value of one variable into another:
Important Rules About Variable Names
-
Variable names are case-sensitive:
msg
,Msg
, andMSG
are all different. -
Names can include letters, digits, underscores (
_
), and dollar signs ($
). -
Variable names cannot start with a digit.
-
Reserved words like
var
,function
, orreturn
cannot be used as variable names.
Dynamic Typing in JavaScript
JavaScript is a dynamically typed language. This means a variable can hold any type of value, and the type can change later:
Constant Variables with const
Use const
when you want the variable to stay the same once it's been assigned a value.
Important: const
variables must be initialized when declared. This is not allowed:
However, if a const
variable is assigned an object or array, you can still modify the contents of that object:
As a convention, constant variables are often written in UPPERCASE to make them stand out.
Variable Scope
Variables can be either global or local depending on where they’re declared.
Global Variables
Declared outside any function, accessible anywhere:
Local Variables
Declared inside a function, only accessible within that function:
Declaring Variables Without let
or var
You can technically declare a variable without let
, const
, or var
, but it’s not recommended:
This can lead to bugs and unexpected behavior. Always use let
or const
for safer code.