ES6 JavaScript: Understanding Let & Const

December 27, 2018

via GIPHY

There were many updates brought by ES6. One of the Syntax updates introduced was the concept of declaring variables with let andconst instead of var

To understand whylet & constwere introduced, we must first understand how var works & the concept of hoisting → That being said, here are the 5 questions we will cover in order:

  1. HOW DOES VAR WORK?
  2. WHAT IS HOISTING
  3. WHAT IS LET & CONST?
  4. WHY WERE LET & CONST ADDED IN ES6?
  5. WHEN SHOULD YOU USE LET & CONST?

1. How does Var work?

  • Prior to ES6, var was the main way to declare variables.
    Ex. var name = "Linda";
  • One of the things that made Javascript confusing prior to ES6 was how it determines variable scope. Scope refers to when and where within your code a variable exists.
  • To Understand the scoping issue var has, we must understand the difference between…
BLOCK SCOPE vs. FUNCTION SCOPE
  • In most programming languages variables have a block scope → variables created in a code block or inside curly braces {}. They cease to exist outside of them → they are scoped to the block.
  • BUT var in javaScript has function scope → variables live within functions & are scoped to the function. Any variable you create with the keyword VAR is local to the function that they were created in. A variable that was created in a parent function lives also in the child function.
  • Let’s clarify by looking at an example:
FUNCTION SCOPE
Local JS Variables
Variables declared within a JavaScript function, become
LOCAL to the function.
example:
// code here CANNOT use petName
function myPet() {
var petName = “Domino”;
// code here CAN use petName
}
Global JS Variables
A variable declared outside a function, becomes GLOBAL.A global variable has global scope: All scripts and functions on a web page can access it.
example:
var petName = “Domino”;
   // code here can use petName
   function petName() {
      // code here can also use petName
   }
---------
--> the examples above show that var is not limited to the curly brackets. It is the function which defines the scope.

You might be wondering ..ok this is nice but why is function scope a problem… I have one word for you:

HOISTING

var uses something called ‘hoisting’, which can lead to unexpected results.

2. What is Hoisting?

  • Variable declarations are one of the most basic aspects of any programming language. One thing that can be dangerous in JavaScript is that variable definitions are hoisted.
  • Javascript actually rearranges your variable declarations during the browser processing phase and moves them to the top of their functional scope. This means that variables can actually exist before you use them.
  • Here’s an example:

Let’s see what happens if I put the variable after the console.log…

function myCourse() {
console.log(courseName + " is a great class");
var courseName = “JavaScript”;
}
myCourse();
This will output: undefined

What we get is kind of strange. The reason this happened is because before it ran any of the code javaScript did this..

function myCourse() {
var courseName;
console.log(courseName + " is a great class");
courseName = “JavaScript”;
}
myCourse();
This will output: undefined is a great class

The variable is actually sitting there but it doesn’t have a value yet and this can cause problems when you create more complex applications. → Hoisting can turn an innocent looking declaration into a subtle bug.

Let’s see what happens if we put a variable outside of the function..

var courseName = “Intro to JavaScript";
function myCourse() {
console.log(courseName + " is a great class");
var courseName = “JavaScript”;
}
myCourse();
This will output: undefined is a great class

Why? because the variable of courseName is still appearing prior to the console.log since it is being hoisted, but it is not defined till after.

Now that we understand var, let’s walk through what Let & Const are, why they were added & when you should use them:

3. What is Let & Const?

  • let allows you to declare variables that are limited in scope to the block, statement, or expression on which it is used. This is unlike the var keyword, which defines a variable globally, or locally to an entire function regardless of block scope.
    Example:
**var can be accessed by the window object since it’s function scope
**let variables cannot be accessed in the window object because they are block scoped & cannot be globally accessed.
  • The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable, just that the variable identifier cannot be reassigned. Here is an example:
Example of Const variable unable to be reassigned
  • Variables declared with let can be reassigned, but can’t be redeclared in the same scope. Here is an example:
Example of Let variable being reassigned
  • Variables declared with const must be assigned an initial value, but can’t be redeclared in the same scope, and can’t be reassigned.

4. Why were Let & Const added?

  • Solves issues caused by Hoisting →
  • Hoisting means “moving to the beginning of a scope.” In JS, function declarations are hoisted completely, variable declarations only partially. Javascript actually rearranges your variable declarations during the browser processing phase and moves them to the top of their functional scope. (check out my blog on hoisting)
  • Variables declared with let and const eliminate this specific issue of hoisting because they’re scoped to the block, not to the function.

5. When should you use Let & Const?

  • use let when you plan to reassign new values to a variable, and
  • use const when you don’t plan on reassigning new values to a variable.
  • ***Is there any reason to use var anymore? Not really.

Hope this helped clarify why Let & Const were introduced. Please feel free to message me with any questions in the comments below or via my IG:
https://www.instagram.com/lindavivah

XOXO & Happy Coding!




Also in Stories by Linda Vivah on Medium

Best Coding Books for Babies/Kids

October 18, 2018

I get a ton of questions regarding the coding books I read to my 15 month old son, specifically on my Instagram.

Since I have purchased quite a few, here are my top 4 coding book suggestions for babies/young kids:

1. ABCs of the Web

A great introduction to basic coding and web concepts for children in the form of the alphabet!

2. Web Design for Kids

Introduces basic coding concepts in an engaging...

Read More

Resources I used to pass the AWS Solutions Architect — Associate Certification Exam

August 29, 2018

I recently passed the AWS Solutions Architect Associate Exam and would like to share some of the resources I used to study for the exam. I used 2 different online courses to study, did the labs included with those courses, & took a few practice tests.

Background: My goal when studying was to really understand and be able to use what I learned on the job. I currently work as a web developer so I do...

Read More

Learn How to Read Binary in 5 minutes

June 22, 2018

via GIPHY

 

What is Binary?

  • Binary is nothing more than a System of Counting
  • Everything in a computer’s brain comes down 0’s & 1’s
  • Binary existed before computers
  • Binary is an ON or OFF counting system, all or nothing. ‘1’ represents ON, ‘0’ represents OFF.
  • Because each digit in binary can have 2 values, the base is 2 (see the example below for...

Read More

10% Off Your First Order!

Use Coupon Code HIGHFIVE