Series: JavaScript 101
- About JavaScript 101
- Hello World in Web Browser
- Hello World in Node.js
- Variable in JavaScript
- Data Types in JavaScript
- Array in JavaScript
- Object in JavaScript
- Spread Operator in JavaScript
- Loops in JavaScript
- Conditional Statements in JavaScript
- Functions in JavaScript
- Object-Oriented Programming in JavaScript
The analogy 📦
Think of a variable in JavaScript as a labeled box 📦 where you can store a value. Just like how you would label a box with a name to keep track of what is inside, you give a variable a name to store a value.
A variable is simply a way to store a value in your code. To create a variable in JavaScript, use the const
/ let
/ var
keyword followed by the name of the variable and assign it a value using the equal sign.
For example, you could create a variable called "name" and give it the value "John Smith". You can then use that variable in your code to refer to that value.
const name = "John Smith";
console.log(name); // John Smith
var, let and const
JavaScript has three types of variables: var
and let
and const
. The var
keyword is used for variables that are function scoped, meaning that their scope is limited to the function in which they are defined. On the other hand, let
and const
are block scoped, meaning that their scope is limited to the block in which they are defined.
Note: The best practice in JavaScript is to use const
by default, and only use let
when you need to reassign the variable. var
should be avoided as much as possible.