Using Constants in ECMAScript 6
In the previous article we covered the work environment that’s we’ll be using to study ECMAScript 6. So now the time has come to learn about our first feature of ES6—constants. Constants in computer programming are variables the cannot be changed. We use them in general for things that are not supposed to be changed, and when their change would cause problems.
The syntax is quite simple:
const TEST = 10;
console.log(TEST);
Instead of the original var, we define a constant with const. It is generally accepted when coding in scripting languages to define constants with capital letters.
If I try to redefine the variable, I’ll generate an error. If I try to enter in a different value than the original used to define the variable, nothing will happen—if I’m not using strict mode. If you’re not familiar with strict mode, this is an excellent opportunity to work with it. This mode enforces stricter rules on the script and displays errors more prominently. We recommend using it to make sure that your scripts are more resistant to changes in language and among the browsers.
Anyway, here is an example—try it yourself! Come on, don’t be shy. You can even open your development console and paste it in.
"use strict";
const TEST = 10;
TEST = 8; //Error on strict mode, ignore in non strict mode.
console.log(TEST);
var TEST = 8; //Error in all modes.
And if you’re feeling lazy, here is the codepen:
Someone pointed out to me that it’s important to note that when we make an assignment to an object, then that object’s content can change.
And one more thing to note is that we can also create constants in the following manner:
const {PROP1, PROP2} = {'PROP1': 1, 'PROP2: 2}
This is pretty useful for each time we want to create a constant. This is a really handy thing to know and a great example of how we don’t need to be afraid of ECMAScript 6.
In the next article, we take a look at a much more significant feature, so check in with us soon.
About the author: Ran Bar-Zik is an experienced web developer whose personal blog, Internet Israel, features articles and guides on Node.js, MongoDB, Git, SASS, jQuery, HTML 5, MySQL, and more. Translation of the original article by Aaron Raizen.
Recent Stories
Top DiscoverSDK Experts
Compare Products
Select up to three two products to compare by clicking on the compare icon () of each product.
{{compareToolModel.Error}}
{{CommentsModel.TotalCount}} Comments
Your Comment