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 two ways: let
and const
, each with its own characteristics:
JavaScript1let age = 20; 2const year = 1900; // A constant. Its value can't change. 3 4age = 21; // Variables created with let can be reassigned.
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:
JavaScript1let flowerJar = null; // we have an empty flower jar 2console.log(flowerJar); // outputs: null 3 4let candyJar; // we have a label for a candy jar, but no actual jar 5console.log(candyJar); // outputs: undefined
Choosing good variable names makes your code easier to understand. When naming JavaScript variables, remember that:
$
, and _
.Here are some good examples:
JavaScript1let myFavoriteColor; 2let message1; 3let $location;
Assignment operators assign values to variables. The most common operator is =
, but JavaScript also includes +=
, -=
, *=
, /=
, and %=
. Have a look:
JavaScript1let x = 10; // x is 10 2x += 5; // adding 5 to x makes x 15 3x -= 3; // subtracting 3 from x makes x 12 4x *= 2; // multiplying x by 2 makes x 24
JavaScript1let x = 5; // x is now 5
==
) checks equality in value, whereas the triple equals operator (===
) checks equality in both value and type.JavaScript1console.log(5 == '5'); // true 2console.log(5 === '5'); // false
!=
) checks for inequality in value, whereas the triple not equals operator (!==
) checks for inequality in either value or type.JavaScript1console.log(5 != '5'); // false 2console.log(5 !== '5'); // true
Congratulations! We've explored JavaScript variables, learning about declaring and assigning them, and delved into understanding assignment and equality operators.
Now, it's time to practice. Engage with these concepts to gain confidence in using them in coding projects. Remember: practice makes perfect! Happy coding!