Search icon CANCEL
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
Advanced JavaScript

You're reading from   Advanced JavaScript Speed up web development with the powerful features and benefits of JavaScript

Arrow left icon
Product type Paperback
Published in Jan 2019
Publisher
ISBN-13 9781789800104
Length 330 pages
Edition 1st Edition
Languages
Arrow right icon
Author (1):
Arrow left icon
Zachary Shute Zachary Shute
Author Profile Icon Zachary Shute
Zachary Shute
Arrow right icon
View More author details
Toc

Declaring Variables


Basic JavaScript uses the keyword var for variable declaration. ECMAScript 6 introduced two new keywords to declare variables; they are let and const. In the world of Professional JavaScript variable declaration, var is now the weakest link. In this topic, we will go over the new keywords, let and const, and explain why they are better than var.

The three ways to declare variables in JavaScript are by using var, let, and const. All function in slightly different ways. The key differences between the three variable declaration keywords are the way they handle variable reassignment, variable scope, and variable hoisting. These three features can be explained briefly as follows:

Variable reassignment: The ability to change or reassign the variable's value at any time.

Variable scope: The extent or area of the code from which the variable may be accessed.

Variable hoisting: The variable instantiation and assignment time in relation to the variable's declaration. Some variables can be used before they are declared.

The var keyword is the older variable declaration keyword that's used to declare variables in JavaScript. All variables created with var can be reassigned, have function scope, and have variable hoisting. This means that variables created with var are hoisted to the top of the scope block, where they are defined and can be accessed before declaration. The following snippet demonstrates this, as follows:

// Referenced before declaration
console.log( example ); // Expect output: undefined
var example = 'example';

Snippet 1.6: Variables created using var are hoisted

Since variables that are created with the keyword var are not constants, they can be created, assigned, and reassigned a value at will. The following code demonstrates this aspect of the functionality of var:

// Declared and assigned
var example = { prop1: 'test' };
console.log( 'example:', example );
// Expect output: example: {prop1: "test"}
// Value reassigned
example = 5;
console.log( example ); // Expect output: 5

Snippet 1.7: Variables created using var are not constant

Variables created with var can be reassigned at any time and once the variable is created, it can be accessed from anywhere in the function, even before the original declaration point.

The let keyword functions similar to the keyword var. As expected, the keyword let allows us to declare a variable that can be reassigned at any time. This is shown in the following code:

// Declared and initialized
let example = { prop1: 'test' };
console.log( 'example:', example );
// Expect output: example: {prop1: 'test"}
// Value reassigned
example = 5;
console.log( example ); // Expect output: 5

Snippet 1.8: Variables created with let are not constant

There are two significant differences between let and var. Where let and var differ is their scoping and variable hoisting properties. Variables declared with let are scoped at the block level; that is, they are only defined in the block of code contained within a matching pair of curly braces ({}).

Variables declared with let are not subject to variable hoisting. This means that accessing a variable declared with let before the assignment will throw a runtime error. As discussed earlier, this is the Temporal Dead Zone. An example of this is shown in the following code:

// Referenced before declaration
console.log( example );
// Expect ReferenceError because example is not defined
let example = 'example';

Snippet 1.9: Variables created with let are not hoisted

The last variable declaration keyword is const. The const keyword has the same scoping and variable hoisting rules as the let keyword; variables declared with const have block scoping and do not get hoisted to the top of the scope. This is shown in the following code:

// Referenced before declaration
console.log( example );
// Expect ReferenceError because example is not defined
const example = 'example';

Snippet 1.10: Variables created with const are not hoisted

The key difference between const and let is that const signifies that the identifier will not be reassigned. The const identifier signifies a read-only reference to a value. In other words, the value written in a const variable cannot be changed. If the value of a variable initialized with const is changed, a TypeError will be thrown.

Even though variables created with const cannot be reassigned, this does not mean that they are immutable. If an array or object is stored in a variable declared with const, the value of the variable cannot be overwritten. However, the array content or object properties can be changed. The contents of an array can be modified with functions such as push(), pop(), or map() and object properties can be added, removed, or updated. This is shown in the following code:

// Declared and initialized
const example = { prop1: 'test' };

// Variable reassigned
example = 5;
// Expect TypeError error because variable was declared with const

// Object property updated
example.prop1 = 5;
// Expect no error because subproperty was modified

Snippet 1.11: Variables created with const are constant but not immutable

To understand the different keywords in more detail, refer to the following table:

Figure 1.3: Differences between var, let, and const

Now that we understand the nuances among var, let, and const, we can decide on which one to use. In the professional world, we should always use let and const, because they provide all the functionality of var and allow the programmer to be specific and restrictive with the variable scope and usage.

In summary, var, let, and const all function similarly. The key differences are in the nature of const, the scope, and the hoisting. Var is function scoped, not constant, and hoisted to the top of the scope block. let and const are both block-scoped and not hoisted. let is not constant, while, const is constant but immutable.

Exercise 2: Utilizing Variables

To utilize the var, const, and let variable declaration keywords for variable hoisting and reassignment properties, perform the following steps:

  1. Log the string Hoisted before assignment: and the value of the hoisted variable.

  2. Define a variable called hoisted with the keyword var and assign it the value this got hoisted.

  3. Log the string hoisted after assignment: and the value of the hoisted variable.

  4. Create a try-catch block.

  5. Inside the try block, log the value of the variable called notHoisted1.

  6. Inside the catch block, give the catch block the err parameter, then log the string Not hoisted1 with error: and the value of err.message.

  7. After the try-catch block, create the notHoisted1 variable with the let keyword and assign the value 5.

  8. Log the string notHoisted1 after assignment and the value of notHoisted1.

  9. Create another try-catch block.

  10. Inside the try block, log the value of the notHoisted2 variable.

  11. Inside the catch block, give the catch block the err parameter, then log the string Not hoisted2 with error: and the value of err.message.

  12. After the second try-catch block, create the notHoisted2 variable with the keyword const and assign the value [1,2,3].

  13. Log the string notHoisted2 after assignment and the value of notHoisted2.

  14. Define a final try catch block.

  15. Inside the try block, reassign notHoisted2 to the new value string.

  16. Inside the catch block, give the catch block the err parameter, then log the string Not hoisted 2 was not able to be changed.

  17. After the try-catch block, push the value 5 onto the array in notHoisted2.

  18. Log the string notHoisted2 updated. Now is: and the value of notHoisted2.

Code

index.js:
var hoisted = 'this got hoisted';
try{
 console.log(notHoisted1);
} catch(err){}
let notHoisted1 = 5;
try{
 console.log(notHoisted2);
} catch(err){}
const notHoisted2 = [1,2,3];
try{
 notHoisted2 = 'new value';
} catch(err){}
notHoisted2.push(5);

Snippet 1.12: Updating the contents of the object

Outcome

Figure 1.4: Hoisting the variables

You have successfully utilized keywords to declare variables.

In this section, we discussed variable declaration in ES6 and the benefits of using the let and const variable declaration keywords over the var variable declaration keyword. We discussed each keywords variable reassignment properties, variable scoping, and variable hoisting properties. The keywords let and const are both create variables in the block scope where var creates a variable in the function scope. Variables created with var and let can be reassigned at will. However, variables created with const cannot be reassigned. Finally, variables created with the keyword var are hoisted to the top of the scope block in which they were defined. Variables created with let and const are not hoisted.

You have been reading a chapter from
Advanced JavaScript
Published in: Jan 2019
Publisher:
ISBN-13: 9781789800104
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 AU $24.99/month. Cancel anytime