Search icon CANCEL
Subscription
0
Cart icon
Your Cart (0 item)
Close icon
You have no products in your basket yet
Save more on your purchases now! discount-offer-chevron-icon
Savings automatically calculated. No voucher code required.
Arrow left icon
Explore Products
Best Sellers
New Releases
Books
Videos
Audiobooks
Learning Hub
Conferences
Free Learning
Arrow right icon
Arrow up icon
GO TO TOP
Learn ECMAScript

You're reading from   Learn ECMAScript Discover the latest ECMAScript features in order to write cleaner code and learn the fundamentals of JavaScript

Arrow left icon
Product type Paperback
Published in Feb 2018
Publisher
ISBN-13 9781788620062
Length 298 pages
Edition 2nd Edition
Languages
Arrow right icon
Authors (2):
Arrow left icon
Narayan Prusty Narayan Prusty
Author Profile Icon Narayan Prusty
Narayan Prusty
MEHUL MOHAN MEHUL MOHAN
Author Profile Icon MEHUL MOHAN
MEHUL MOHAN
Arrow right icon
View More author details
Toc

Table of Contents (14) Chapters Close

Preface 1. Getting Started with ECMAScript 2. Knowing Your Library FREE CHAPTER 3. Using Iterators 4. Asynchronous Programming 5. Modular Programming 6. Implementing the Reflect API 7. Proxies 8. Classes 9. JavaScript on the Web 10. Storage APIs in JavaScript 11. Web and Service Workers 12. Shared Memory and Atomics 13. Other Books You May Enjoy

The const keyword

Using the const keyword, you can create variables that cannot change their values (hence they're  called constants) once they're initialized, that is, you cannot reinitialize them with another value later in your code.

If you try to reinitialize a const variable, a read-only exception is thrown. Furthermore, you cannot just declare and not initialize a const variable. It'll also throw an exception.

For instance, you might want your JavaScript to crash if someone tries to change a particular constant, say pi, in your calculator. Here's how to achieve that:

const pi = 3.141;
pi = 4; // not possible in this universe, or in other terms,
// throws Read-only error

The scope of const variables

The const variables are block-scoped variables, that is, they follow the same scoping rules as the variables that are declared using the let keyword. The following example demonstrates the scope of the constant variables:

const a = 12; // accessible globally
function myFunction() {
console.log(a);
const b = 13; // accessible throughout function
if(true) {
const c = 14; // accessible throughout the "if" statement
console.log(b);
}
console.log(c);
}
myFunction();

The output of the preceding code is:

12
13
ReferenceError Exception

Here, we can see that constant variables behave in the same way as block-scoped variables when it comes to scoping rules.

Referencing objects using constant variables

When we assign an object to a variable, the reference of the object is what the variable holds and not the object itself. So, when assigning an object to a constant variable, the reference of the object becomes constant to that variable and not to the object itself. Therefore, the object is mutable.

Consider this example:

const a = {
name: "Mehul"
};
console.log(a.name);
a.name = "Mohan";
console.log(a.name);
a = {}; //throws read-only exception

The output of the preceding code is:

Mehul
Mohan
<Error thrown>

In this example, the a variable stores the address (that is, reference) of the object. So the address of the object is the value of the a variable, and it cannot be changed. But the object is mutable. So when we tried to assign another object to the a variable, we got an exception as we were trying to change the value of the a variable.

When to use var/let/const 

The difference between const and let is that const makes sure that rebinding will not happen. That means you cannot reinitialize a const variable, but a let variable can be reinitialized (but not redeclared).

Within a particular scope, a const variable always refers to the same object. Because let can change its value at runtime, there is no guarantee that a let variable always refers to the same value. Therefore, as a rule of thumb, you can (not strictly) follow these:

  • Use const by default if you know that you'll not change the value (max performance boost)
  • Only use let if you think reassignment is required/can happen somewhere in your code (modern syntax)
  • Avoid using var (let does not create global variables when defined in a block scope; this makes it less confusing for you if you come from a C, C++, Java, or any similar background)

Let versus var versus const performance benchmarks

Currently, running a benchmark test on my own laptop (MacBook Air, Google Chrome Version 61.0.3163.100 (official build) (64-bit)) produces the following result:

Clearly, performance-wise on Chrome, let on the global scope is slowest, while let inside a block is fastest, and so is const.

First of all, the aforementioned benchmark tests are performed by running a loop 1000 x 30 times and the operation performed in the loop was appending a value to an array. That is, the array starts from [1], then becomes [1,2] in the next iteration, then [1,2,3], and so on.

What do the results mean? One inference we can draw from these results is that let is slower in a for loop when used inside the declaration: for(let i=0;i<1000;i++).

This is because let is redeclared every time for each iteration (relate this to the closure section you read earlier), whereas for(var i=0;i<1000;i++) declares the i variable for the whole block of code. This makes let a bit slower when used in a loop definition.

However, when let is not used inside the loop body but declared outside the loop, it performs quite well. For example:

let myArr = [];
for(var i = 0;i<1000;i++) {
myArr.append(i);
}

This will give you the best results. However, if you're not performing tens of hundreds of iterations, it should not matter.

lock icon The rest of the chapter is locked
Register for a free Packt account to unlock a world of extra content!
A free Packt account unlocks extra newsletters, articles, discounted offers, and much more. Start advancing your knowledge today.
Unlock this book and the full library FREE for 7 days
Get unlimited access to 7000+ expert-authored eBooks and videos courses covering every tech area you can think of
Renews at $19.99/month. Cancel anytime