JS-101-Fundamentals
  • JavaScript Library
  • 1-JavaScript Fundamentals
    • 0-Getting Started
      • Welcome
    • 1-JS-Fundamentals
      • 1-Grammar and Types
        • Comments
        • Declarations
        • Scope
        • Hoisting
        • Types
        • Literals
      • 2-Control Flow and Error Handling
        • if
        • if else
        • switch
        • try catch
        • throw
      • 3-Loops
        • For Loops
        • For In Loops
        • For Of Loops
        • Do While
        • While Loops
      • 4-Functions
        • Declarations
        • Expressions
        • Calling Functions
        • Scope
        • Parameters
        • Arguments
        • Closures
        • Closures Challenge
        • Arrow Functions
        • Predefined
      • 5-Expressions and Operators
        • Assignment
        • Comparison
        • Ternary
        • Typeof
        • Left Hand Side
        • Spread
      • 6 Numbers and Dates
        • Numbers
          • Numbers Enhanced
        • Math
        • Dates
      • 7 String Methods
        • String Literals
        • Methods
      • 8 Regular Expressions
        • Basic Intro
      • 9 Arrays
        • Array Review
        • Populating/Referring
        • Length
        • Iterating
        • Methods
      • 10 Objects
        • About Objects
        • Properties
        • Enumeration
        • Initializers
        • Constructor Functions
        • this
        • create
        • Methods
      • 11 ES6 Intro
        • ES6 Intro
        • let
        • const
Powered by GitBook
On this page
  • const must be initialized upon declaration
  • Immutability
  • Value is mutable
  • More Practice
  • More Practice
  1. 1-JavaScript Fundamentals
  2. 1-JS-Fundamentals
  3. 11 ES6 Intro

const

Another ES6 addition was the const keyword. const stands for constant, which can be deceptive to developers. Let's look at a few rules of constants in JavaScript.

const must be initialized upon declaration

Like var and let, the const keyword is a container. However, const values must be initialized when they are declared. Consider the following:

const constNumber;
constNumber = 10;
console.log(constNumber); //Error missing initializer in const declaration

Here we have a declaration for a const, but we don't have an initiaztion with the declaration. Something like this would be accurate and work properly:

//This works:
const constWithInitializer = 'Initializing as a string';
console.log(constWithInitializer);

Immutability

This is the hard part of const. So for booleans, strings, and numbers, we will break the app if we try to change it by reassignment:

const constWithInitializer = 'Initializing as a string';
console.log(constWithInitializer);

//Reassigning the value
//This will throw an error
constWithInitializer = "New value";
console.log(constWithInitializer);

Value is mutable

We can, however, manipulate the value of the string, meaning we can take the constWithInitializer variable and call methods on it. Let's use the concat() method:

const constWithInitializer = 'Initializing as a string';
console.log(constWithInitializer);

const ok = ", ok?";
console.log(constWithInitializer.concat(ok));

This is also something that we can demonstrate with arrays. Creating a const variable doesn’t mean that the assigned value becomes immutable. Check out the following:

const singers = ['Jagger', 'Plant', 'McCartney', 'Lennon']
console.log(singers);

singers.push('Cobain')
console.log(singers)

The previous example shows that even though the singers reference couldn’t be changed, the array itself can indeed be modified.

What we can't do is create an entirely new reference to a whole different array. The following would break:

singers = ['Clapton'];
console.log(singers);

Using var would allow us to do this:

var guitarists = ['Page', 'Hendrix', 'Clapton'];
console.log(guitarists);

guitarists = ['King'];
console.log(guitarists);

More Practice

To further examine this idea of mutability and immutability, let's get a little more practice with const and look at it from another angle with a little more complex example. First, let's give you the code for this section:

//1
const favoriteFoods = ['apples', 'beets', 'cauliflower', 'dairy'];

//3
const diet = checkFoodList(favoriteFoods);

//4
const shortNames = diet.checkForShorterNames();
console.log("Short names:", shortNames)

//5
const longNames = diet.checkForLongerNames();
console.log("Long names:", longNames);

//2
function checkFoodList(items) {
  return {
    checkForShorterNames: () => items.filter(item => item.length <= 6),
    checkForLongerNames: () => items.filter(item => item.length > 6)
  }
}
  1. We created the favoriteFoods array as a const.

  2. We created a method called checkFoodList. That method returns two different methods checkForShorterNames & checkForLongerNames. These methods do some basic filtering. (Note: these methods are using arrow functions.)

  3. We create another const called diet. We store the result of passing in the favoriteFoods array into checkFoodList. This way we can call the methods on the diet constant.

  4. The diet constant now has access to the two methods, and we create another const called shortNames to store

    the result of running checkForShorterNames().

  5. We create another const called longNames to store the result of running checkForLongerNames() that will be used to store the result of calling the method on diet.

The point here is threefold: 1. Get a little more practice with programming logic and passing data around from container to container. 2. Understand that const values can change and be broken up in different ways, it's just that they can't be reinitialized.

More Practice

Write a similar, almost verbatim chunk of code to the one above, called filterSingerNames. The function will return a function that filters singer names that are 4 letters long or under, and it will return a function that will return a function that filters singer names that are five letters or more.

Previouslet

Last updated 7 years ago