- JavaScript Variables
- Example
- Note
- Example using var
- Note
- Example using let
- Example using const
- Mixed Example
- When to Use var, let, or const?
- Just Like Algebra
- Note
- JavaScript Identifiers
- Note
- The Assignment Operator
- Note
- JavaScript Data Types
- Example
- Declaring a JavaScript Variable
- Example
- Note
- One Statement, Many Variables
- Example
- Example
- Value = undefined
- Example
- Re-Declaring JavaScript Variables
- Example
- Note
- JavaScript Arithmetic
- Example
- How the let, const, and var Keywords Work in JavaScript
- How to Reassign a New Value to a Variable in JavaScript
- What Happens When You Access a Variable Before Declaring it in JavaScript
- Before We End.
JavaScript Variables
In this first example, x , y , and z are undeclared variables.
They are automatically declared when first used:
Example
Note
It is considered good programming practice to always declare variables before use.
From the examples you can guess:
Example using var
Note
The var keyword was used in all JavaScript code from 1995 to 2015.
The let and const keywords were added to JavaScript in 2015.
The var keyword should only be used in code written for older browsers.
Example using let
Example using const
Mixed Example
The two variables price1 and price2 are declared with the const keyword.
These are constant values and cannot be changed.
The variable total is declared with the let keyword.
The value total can be changed.
When to Use var, let, or const?
1. Always declare variables
2. Always use const if the value should not be changed
3. Always use const if the type should not be changed (Arrays and Objects)
4. Only use let if you can’t use const
5. Only use var if you MUST support old browsers.
Just Like Algebra
Just like in algebra, variables hold values:
Just like in algebra, variables are used in expressions:
From the example above, you can guess that the total is calculated to be 11.
Note
Variables are containers for storing values.
JavaScript Identifiers
All JavaScript variables must be identified with unique names.
These unique names are called identifiers.
Identifiers can be short names (like x and y) or more descriptive names (age, sum, totalVolume).
The general rules for constructing names for variables (unique identifiers) are:
- Names can contain letters, digits, underscores, and dollar signs.
- Names must begin with a letter.
- Names can also begin with $ and _ (but we will not use it in this tutorial).
- Names are case sensitive (y and Y are different variables).
- Reserved words (like JavaScript keywords) cannot be used as names.
Note
JavaScript identifiers are case-sensitive.
The Assignment Operator
In JavaScript, the equal sign ( = ) is an «assignment» operator, not an «equal to» operator.
This is different from algebra. The following does not make sense in algebra:
In JavaScript, however, it makes perfect sense: it assigns the value of x + 5 to x.
(It calculates the value of x + 5 and puts the result into x. The value of x is incremented by 5.)
Note
The «equal to» operator is written like == in JavaScript.
JavaScript Data Types
JavaScript variables can hold numbers like 100 and text values like «John Doe».
In programming, text values are called text strings.
JavaScript can handle many types of data, but for now, just think of numbers and strings.
Strings are written inside double or single quotes. Numbers are written without quotes.
If you put a number in quotes, it will be treated as a text string.
Example
Declaring a JavaScript Variable
Creating a variable in JavaScript is called «declaring» a variable.
You declare a JavaScript variable with the var or the let keyword:
After the declaration, the variable has no value (technically it is undefined ).
To assign a value to the variable, use the equal sign:
You can also assign a value to the variable when you declare it:
In the example below, we create a variable called carName and assign the value «Volvo» to it.
Then we «output» the value inside an HTML paragraph with >
Example
let carName = «Volvo»;
document.getElementById(«demo»).innerHTML = carName;
Note
It’s a good programming practice to declare all variables at the beginning of a script.
One Statement, Many Variables
You can declare many variables in one statement.
Start the statement with let and separate the variables by comma:
Example
A declaration can span multiple lines:
Example
Value = undefined
In computer programs, variables are often declared without a value. The value can be something that has to be calculated, or something that will be provided later, like user input.
A variable declared without a value will have the value undefined .
The variable carName will have the value undefined after the execution of this statement:
Example
Re-Declaring JavaScript Variables
If you re-declare a JavaScript variable declared with var , it will not lose its value.
The variable carName will still have the value «Volvo» after the execution of these statements:
Example
Note
You cannot re-declare a variable declared with let or const .
JavaScript Arithmetic
As with algebra, you can do arithmetic with JavaScript variables, using operators like = and + :
Example
You can also add strings, but strings will be concatenated:
How the let, const, and var Keywords Work in JavaScript
TAPAS ADHIKARY
As a JavaScript beginner, you probably learned how to declare variables and assign values.
In the old, pre-ES6 era of JavaScript, developers used to declare variables using the keyword var or without any keywords. But times have changed!
With ES6 (EcmaScript 2015), the beginning of the modern era in JavaScript, the language got two new keywords to help us declare variables. These are let and const .
In this article, we will learn about all of these keywords (yes, including var ) with examples, and we’ll see when to use them, and when not to use them.
If you like to learn from video content as well, this article is also available as a YouTube video tutorial here: 🙂
Let’s move on to the next concept to understand how these three keywords influence the code’s behavior when we reassign a new value to a variable.
How to Reassign a New Value to a Variable in JavaScript
Once you’ve declared a variable with var or let , you can reassign a new value to the variable in your programming flow. It is possible if the variable is accessible to assign a value. But with const , you can’t reassign a new value at all.
// Declare variables with initial values let f_name = "Alex"; const ZIP = 560089; var age = 25; // Reassign values f_name = "Bob"; // the f_name value is 'Bob" ZIP = 65457; // Uncaught TypeError: Assignment to constant variable. age = 78; // the age value is 78
There is a tricky part with const that you must be aware of. When an object is declared and assigned a value with const , you can still change the value of its properties . But you can not reassign another object value to the same variable. This is a common mistake many devs make.
Check out the example here:
const blog = < 'url': 'https://greenroots.info' >blog.url = 'https://blog.greenroots.info"; //Allowed blog = <>; // Uncaught TypeError: Assignment to constant variable.
Here is a mindmap to help you grasp how reassigning works for variables declared with these three keywords.
What Happens When You Access a Variable Before Declaring it in JavaScript
As a pragmatic programmer, you should never try accessing a variable without declaring it. But in case it happens, let’s see how the variable may behave.
With var in non-strict mode, the variable will have an undefined value. This means that a variable has been declared but has no value assigned.
In strict mode, you will get a ReferenceError that the variable is not declared.
With let and const , if you try to access a variable before declaring, you will always get a ReferenceError .
Here is a mindmap again to help you understand it visually. In the mindmap, var is depicted for non-strict mode.
That’s all, my friends. You need to consider these circumstances and concepts to evaluate how var , let , and const behave. So, the rule goes:
- Don’t use var anymore.
- Use let or const .
- Use const more often. Use let when you need to reassign another value to a variable.
- Don’t try to access a variable without declaring it.
Before We End.
That’s the story behind let , const , and var . I hope you found the article insightful and informative. My DMs are open on Twitter if you want to discuss further.
Let’s connect. I share my learnings on JavaScript, Web Development, and Blogging on these platforms as well:
See you soon with my next article. Until then, please take care of yourself, and stay happy.