1 min read
Easy Guide to var, let, and const in JavaScript
In JavaScript, we use var
, let
, and const
to make variables, but they do different things. Let’s break it down simply.
- var:
- Where it works: You can use
var
anywhere in your function. It doesn’t care if it’s inside a loop or an if statement. - Gets ready early: When you use
var
, JavaScript gets ready to use it even before it’s declared. That’s called hoisting. - Can change and redo: You can change and redo a
var
variable any time in your function.
- Where it works: You can use
- let:
- Where it works:
let
stays only in the block where you put it, like inside curly braces{}
. - Gets ready on time: With
let
, JavaScript waits until you say what the variable is before it gets ready to use it. - Can change, but can’t redo: You can change a
let
variable, but once you say what it is, you can’t change it to be something else.
- Where it works:
- const:
- Where it works: Like
let
,const
stays only in the block where you put it. - Gets ready on time: JavaScript waits until you say what the
const
is before getting it ready to use. - Can’t change, but parts can: Once you say what a
const
is, you can’t change it. But if it’s an object or an array, you can still change what’s inside.
- Where it works: Like
Practical Tips:
- Use
const
most of the time. It keeps things safe. - Use
let
when you need to change what a variable is. - Try to avoid using
var
. It can cause surprises sometimes.
Knowing when to use var
, let
, and const
helps keep your JavaScript code clear and easy to understand. By remembering these simple rules, you’ll be able to manage your variables better and write cleaner code in JavaScript.