JavaScript variables are one of the most fundamental concepts. They let you store, update, and use data throughout your code.
In this post, you’ll learn what variables are, how to declare them, and the key differences between the types you’ll use.
Before we get started, don’t forget to subscribe to my newsletter!
Get the latest tips, tools, and resources to level up your web development skills delivered straight to your inbox. Subscribe here!
Now, let’s jump right into it!
What Are JavaScript Variables?
In JavaScript, variables are used to store data. They act as containers that can hold different types of data, like numbers, text, or even complex data.
For example:
let message = "Hello, world!";
Here, message
is the variable, and "Hello, world!"
is the value stored inside it.
Learning web development?
Check out Learnify — a simple, clean tutorial platform.
Easy-to-follow tutorials with examples to help you understand and build things.
How to Declare JavaScript Variables: var, let, and const
JavaScript gives us three ways to declare variables:
-
var
– the original way (older and mostly avoided today) -
let
– the modern way for values that can change -
const
– for values that should not change once set
A Quick Note on Scope
Before we dive into var
, let
, and const
, it's important to understand what scope means in JavaScript.
Scope is simply the part of the code where a variable is available and can be used.
There are two main types you need to know for now:
- Function Scope – Variables are accessible only inside the function they are declared in.
-
Block Scope – Variables are accessible only inside the
{}
block they are declared in (like insideif
,for
, or{}
).
Now, let’s go through each one step by step.
Using var in JavaScript: Scope, Redeclaration, and Hoisting
The var
keyword was how developers declared variables before ES6 (2015). It still works in JavaScript, but it has some confusing behavior that makes it not a good choice for modern code.
Characteristics of var
- Function-scoped or Global-scoped: Depending on where it is declared.
- Can be redeclared: You can declare the same variable name again.
- Hoisted: The variable is moved to the top of its scope, but only declared (not assigned).
Example 1:
var name = "Learnify";
console.log(name); // Output: Learnify
var name = "LearnifyJS"; // allowed
console.log(name); // Output: LearnifyJS
You can declare the same variable twice, this can accidentally overwrite data.
Example 2:
function testVar() {
var x = 10;
if (true) {
var x = 20; // same variable
console.log(x); // 20
}
console.log(x); // 20 (unexpected?)
}
Here,
-
var
is function-scoped, not block-scoped. That means the entire function shares the same x, even inside theif
block. - Inside the function, x is first declared and set to 10 using
var x = 10;
- Then inside the
if (true)
block, we declarevar x = 20;
. But sincevar
is not block-scoped, we're not creating a new variable, we're reassigning the same x.
var x = 20; // same variable, new value
console.log(x) inside the block prints 20.
- After the
if
block,console.log(x)
still prints 20, because the x inside theif
block was the same x outside theif
block.
Why is it unexpected?
When we use var
, the variable is not limited to the block {}
where it’s declared. Instead, it's available throughout the entire function.
So in the above example, even though it looks like we’re declaring a new x inside the if
block, we're actually reassigning the same x declared earlier.
This can be confusing because the inner var x = 20;
overwrites the original var x = 10;
, even though it's inside a separate block.
Why var is discouraged today
- It's scoped to functions, not blocks
{}
, which can lead to bugs. - Allows redeclaration, which may cause accidental overrides.
- Hoisting behavior can be confusing (the variable exists before it's declared).
let in JavaScript: Block-Scoped Variables and Why They’re Safer
let
is the modern way to declare a variable whose value can change later.
Characteristics of let
-
Block-scoped: Limited to the
{}
block where it’s declared. - Can’t be redeclared: in the same scope.
- Can be updated: value can change.
- Hoisted but not initialized: accessing it before declaration causes an error (Temporal Dead Zone).
Example 1:
let count = 1;
count = 2; // allowed
let count = 3; // Error: count has already been declared (in the same scope)
Example 2:
function testLet() {
let x = 10;
if (true) {
let x = 20; // different variable (block-scoped)
console.log(x); // 20
}
console.log(x); // 10 (works as expected)
}
Here,
-
let
is block-scoped, not function-scoped. That means a new x is created for each block{}
, and they don't interfere with each other. - Inside the function, x is first declared and set to 10 using
let x = 10;
. This x belongs to the function's outer block. - Then inside the
if (true)
block, we declarelet x = 20;
. - But since
let
is block-scoped, this creates a new x that exists only inside theif
block and it’s completely separate from the outer x. - After the
if
block,console.log(x)
prints 10, because the outer x is still unchanged, the inner x existed only inside the block and is now gone.
let
makes code safer and more predictable than var
.
const Variables in JavaScript: Immutable References and When to Use Them
Use const
when you don’t want to change the variable after it’s been assigned.
Characteristics of const
- Block-scoped
- Must be initialized when declared
- Cannot be reassigned
- Still allows mutation of object and array values
Example:
const pi = 3.14;
pi = 3.1415; // Error: can't reassign a const
Here, pi
is a constant. Once it’s set to 3.14
, we cannot change it to anything else. JavaScript will throw an error if we try.
However, when we use const
with objects (like arrays or objects), the situation is a bit different.
const user = { name: "Learnify" };
user.name = "LearnifyJS"; // Allowed
Here, we're not changing the user
variable itself instead we're just changing one of its properties (name).
That’s allowed because the reference stored in user
is constant, but the content inside the object can still be modified.
Comparing JavaScript Variables: var vs let vs const
Keyword | Scope | Can Redeclare | Can Reassign | Hoisted? | Use It When... |
---|---|---|---|---|---|
var |
Function/Global | Yes | Yes | Yes (initialized as undefined ) |
You need compatibility with old code (rare) |
let |
Block | No | Yes | Yes (but TDZ error if accessed early) | You need a value that will change |
const |
Block | No | No | Yes (but TDZ error if accessed early) | The value should stay constant |
JavaScript Variable Naming Rules
When naming variables in JavaScript, there are a few important rules and guidelines to follow:
-
Variable names must start with a letter, underscore
_
, or dollar sign$
.
let name = "Alice"; // Valid let _name = "Bob"; // Valid let $price = 100; // Valid let 1name = "Charlie"; // Invalid: cannot start with a number
-
They can contain letters, numbers, underscores
_
, and dollar signs$
.
let name1 = "John"; // Valid let total_price = 99; // Valid let $discount10 = true; // Valid
-
Variable names are case-sensitive. That means
name
,Name
, andNAME
are three different variables.
let a = 5; let A = 10; console.log(a + A); // Output: 15
-
You cannot use JavaScript keywords as variable names. These are words that JavaScript uses for its own functionality.
Common keywords you should not use:
if
,else
,for
,while
,let
,const
,function
,return
,class
, etc.
let let = 5; // Invalid let if = "yes"; // Invalid let function = 10; // Invalid
Best Practices for Naming JavaScript Variables
-
Be descriptive: Choose meaningful names that describe the purpose of the variable. For example, use
age
instead ofa
, andfirstName
instead offn
. -
Use camelCase for multiple words: In JavaScript, the standard naming style is camelCase. The first word is lowercase, and the rest start with capital letters.
let firstName = "Alice"; // Recommended let userAge = 30; // Recommended // let first_name = "Alice"; // Not common in JS (used in Python)
-
Avoid starting with
_
or$
unless needed: These are technically allowed, but they’re usually reserved for special use (like in libraries or frameworks).
let _privateValue = 42; // Allowed, but not common in normal code let $element = document.querySelector("div"); // Used in libraries like jQuery
🎯Wrapping Up
That’s all for today!
For paid collaboration connect with me at : [email protected]
Hope you find this post helpful!
If you found this post helpful, here’s how you can support my work:
☕ Buy me a coffee – Every little contribution keeps me motivated!
📩 Subscribe to my newsletter – Get the latest tech tips, tools & resources.
𝕏 Follow me on X (Twitter) – I share daily web development tips & insights.
Keep coding & happy learning!
Top comments (0)