Let's explore JavaScript variables — the essential containers for storing data — along with assignment and equality operators, which facilitate our interaction with these variables. After this lesson, you'll understand how to define, use variables, and comprehend the operators.
Think of a variable in JavaScript as a box. This box stores data that can be changed, accessed, and manipulated within a program. Variables are declared in three ways: let, var and const, each with its own characteristics:
You might encounter var in older JavaScript code or tutorials, and it's important to understand why modern JavaScript favors let and const instead.
The Problem with var:
var has quirky scoping rules that can lead to unexpected bugs. It uses "function scope" instead of "block scope," meaning variables declared with var are accessible throughout the entire function, even outside the blocks where they're declared:
Why You Need to Know About var:
Even though we avoid using var in new code, you'll likely see it when:
- Reading older tutorials or Stack Overflow answers
- Working with legacy codebases
- Maintaining existing projects
Best Practice:
- Use
constby default for values that won't change - Use
letwhen you need to reassign a variable - Avoid
varin new code — it's a relic from JavaScript's early days
This understanding helps you read older code while writing better code yourself!
In JavaScript, we frequently encounter situations in which a variable doesn't have a value. In such cases, the null and undefined types come into play.
Imagine you possess a flower jar (variable), but it's empty. There is no flower inside. This absence of content is what null in JavaScript represents — an intentionally empty or non-existent value.
Suppose you have a label for a candy jar, but you don't actually have the jar. This is where undefined comes in. It indicates that a variable has been declared, but doesn't yet hold any value.
Here's a code example to illustrate:
