Skip to content

Instantly share code, notes, and snippets.

@ldco2016
Last active November 8, 2021 07:16
Show Gist options
  • Select an option

  • Save ldco2016/fc1e2b767d2e16242e2adb8dca458ace to your computer and use it in GitHub Desktop.

Select an option

Save ldco2016/fc1e2b767d2e16242e2adb8dca458ace to your computer and use it in GitHub Desktop.
JavaScript: variables (ES6), arrays, conditionals, and loops

Create a Variable: Const

Let's dive in and see a variable in the wild. Here is how you declare a constant variable:

const myName = 'Arya';
console.log(myName);
// Output: Arya

Let's consider the above example:

  1. const, short for constant, is a JavaScript keyword that creates a new variable with a value that cannot change.
  2. myName is the variable's name. Notice that the word has no spaces, and we capitalized the N. Capitalizing in this way is a standard convention in JavaScript called camelCasing, because the capital letters look like the humps on a camel's back.
  3. = is the assignment operator. It assigns the value ('Arya') to the variable (myName).
  4. 'Arya' is the value assigned (=) to the variable myName.

After the variable is declared, we can print 'Arya' to the console with: console.log(myName).

You can save any data type in a variable. For example, here we save numbers:

const myAge = 11;
console.log(myAge);
// Output: 11

In the example above, the myAge variable is set to 11. Below that, console.log() is used to print 11 to the console.

Create a Variable: let

Constant variables, as their name implies, are constant — you cannot assign them a different value.

Let variables however, can be reassigned.

let meal = 'Enchiladas';
console.log(meal);
meal = 'Tacos';
console.log(meal);
// output: Enchiladas
// output: Tacos

In the example above, the let keyword is used to create the meal variable with the string 'Enchiladas' saved to it. On line three, the meal variable is changed to store the string 'Tacos'.

You may be wondering, when to use const vs let. In general, only use const if the value saved to a variable does not change in your program.

Undefined

What happens if you create a variable, but don't assign it a value?

JavaScript creates space for this variable in memory and sets it to undefined. Undefined is the fifth and final primitive data type. JavaScript assigns the undefined data type to variables that are not assigned a value.

let whatAmI;

In the example above, I created the variable whatAmI without any value assigned to it. JavaScript creates the variable and sets it equal to the value undefined.

Mathematical Assignment Operators

In this section, let's consider how we can use variables and math operators to calculate new values and assign them to a variable. Check out the example below:

let x = 4;
x = x + 1;

In the example above, I created the variable x with the number 4 assigned to it. On the following line, x = x + 1 increases the value of x from 4 to 5.

Notice, on line two in the example above, to increment x by one we had to write the x variable on the left and right side of the assignment operator (=). Using a variable twice in one expression is redundant and confusing.

To address this, JavaScript has a collection of built-in mathematical assignment operators that make it easy to calculate a new value and assign it to the same variable without writing the variable twice. See examples of these operators below.

let x = 4;
x += 2; // x equals 6

let y = 4;
y -= 2; // y equals 2

let z = 4;
z *= 2; // z equals 8

let r = 4;
r++; // r equals 5

let t = 4;
t--; // t equals 3

In the example above, operators are used to calculate a new value and assign it to the same variable. Let's consider the first three and last two operators separately:

  1. In the first three operators (+=, -=, and *=) perform the mathematical operation of the first operator (+, -, or *) using the number on the right, then assign the new value to the variable.
  2. The last two operators are the increment (++) and decrement (--) operators. These operators are responsible for increasing and decreasing a number variable by one, respectively.

String Interpolation

In previous exercises, we assigned strings to variables. Here, you will learn how to insert the content saved to a variable into a string.

The JavaScript term for inserting the data saved to a variable into a string is string interpolation.

The + operator, known until now as the addition operator, is used to interpolate (insert) a string variable into a string, as follows:

let myPet = 'armadillo';
console.log('I own a pet ' + myPet + '.'); 
// Output: 'I own a pet armadillo.'

In the example above, we saved the value 'armadillo' to the myPet variable. On the second line, the + operator is used to combine three strings: I own a pet, the value saved to myPet, and .. We log the result of this interpolation to the console as:

I own a pet armadillo

String Interpolation II

In the newest version of JavaScript (ES6) we can insert variables into strings with ease, by doing two things:

  1. Instead of using quotes around the string, use backticks (this key is usually located on the top of your keyboard, left of the 1 key).
  2. Wrap your variable with ${myVariable}, followed by a sentence. No +s necessary.

ES6 string interpolation is easier than the method you used last exercise. With ES6 interpolation we can insert variables directly into our text.

It looks like this:

let myPet = 'armadillo'
console.log(`I own a pet ${myPet}.`)
// Output: 'I own a pet armadillo.'

Go ahead and create a variable called myName and assign it your name.

Ready for the answer? This is how I did mine:

let myName = "Daniel";

Now, create a variable called myCity, and assign it your favorite city's name.

Here is my answer:

let myCity = "Kelowna";

Now use ${} to interpolate your variables into the sentence below. Use console.log() to print your sentence to the console.

My name is NAME. My favorite city is CITY.

Replace NAME and CITY in the values above with the values saved to myName and myCity.

Here is my answer:

let myName = "Daniel";
let myCity = "Kelowna";
console.log(`My name is ${myName}. My favorite city is ${myCity}.`);
// Output: My name is Daniel. My favorite city is Kelowna.

A foundational concept of programming is how to organize and store data.

One way we organize data in real life is to make lists. Let's make one here:

New Year's Resolutions:

  1. Rappel into a cave
  2. Take a falconry class
  3. Learn to juggle

Let's now write this list in JavaScript, as an array:

let newYearsResolutions = ['Rappel into a cave', 'Take a falconry class', 'Learn to juggle'];

Arrays are JavaScript's way of making lists. These lists can store any data types (including strings, numbers, and booleans) and they are ordered, meaning each item has a numbered position.

Create an Array

Let's start by making an array and then seeing what it can do throughout the rest of this lesson.

Make a variable named newYearsResolutions and set it equal to an array with three strings inside of it.

Does your code look something like this?

let newYearsResolutions = ['mentor more students','grow more tomatoes','learn more business skills'];

If so, good job! Now let's console.log to print newYearsResolutions on the screen.

let newYearsResolutions = ['mentor more students','grow more tomatoes','learn more business skills'];
console.log(newYearsResolutions);
// Output: [ 'mentor more students',
//  'grow more tomatoes',
//  'learn more business skills' ]

Did you get something like this? Great!

Property Access

Each item in an array has a numbered position. We can access individual items using their numbers, just like we would in an ordinary list.

Something important to note is that JavaScript starts counting from 0 rather than 1, so the first item in an array will be at position 0. This is because JavaScript is zero-indexed.

We can select the first item in an array like this:

let newYearsResolutions = ['Rappel into a cave', 'Take a falconry class', 'Learn to juggle'];

console.log(newYearsResolutions[0]);
// Output: 'Rappel into a cave'

You can also access individual characters in a string. For instance, you can write:

let hello = 'Hello World';
console.log(hello[6]);
// Output: W

W will be the output since it's the character in the 6th position. This works because JavaScript stores strings in a similar way that it stores arrays.

Individual elements of arrays can also be stored to variables.

Create a variable named listItem and set it equal to the first item in your newYearsResolutions array using square bracket notation ([]).

Then use console.log() to print the listItem variable to the console.

You should have gotten something equivalent to what you see below:

let newYearsResolutions = ['mentor more students','grow more tomatoes','learn more business skills'];
console.log(newYearsResolutions);

let listItem = newYearsResolutions[0];
console.log(listItem);
// Output: [ 'mentor more students',
   // 'grow more tomatoes',
  // 'learn more business skills' ]
// mentor more students

Now, console.log() the third item in the newYearsResolutions array without using a variable.

Did you get something like what is below?

let newYearsResolutions = ['mentor more students','grow more tomatoes','learn more business skills'];
console.log(newYearsResolutions);

let listItem = newYearsResolutions[0];
console.log(listItem);
console.log(newYearsResolutions[2]);
// Output: [ 'mentor more students',
  // 'grow more tomatoes',
  // 'learn more business skills' ]
// mentor more students
// learn more business skills

If so, great!

Now try to log the item at position [3] to the console. What is logged to the console?

I know that was a confusing request. I don't like to teach that way, but sometimes in your development experience, you may get awkward requests like that which may make you call into question your coding abilities. I promise you there is a purpose to why I instructed you to do this. Now, did you get something like this:

console.log(newYearsResolutions[3]);
// Output:  undefined

If so, are you still questioning your abilities? Don't, I deliberately instructed for you to log a position that does not exist, so you can learn what kind of error message you would get. Let's move on.

Update Elements

So you learned how to access elements of an array or a string using their index number. You can also change elements of an array using their indices.

let seasons = ["Winter", "Spring", "Summer", "Fall"];

seasons[3] = "Autumn";
console.log(seasons) 
//Output: 
//Winter 
//Spring
//Summer
//Autumn

In the example above, the seasons array contained the names of the four seasons.

However, we decided that we preferred to say "Autumn" instead of "Fall".

seasons[3] = "Autumn"; tells our program to change the item at index 3 of the seasons array to be "Autumn" instead of what is already there.

Going back to the code you have been working on, change the second element of your newYearsResolutions array to be, 'Learn a new language'.

Does your code look like the one below:

newYearsResolutions[1] = 'Learn a new language';

Great!

length property

We may wish to know how many items are stored inside of an array.

We can find this out by using one of an array's built-in properties, called length. We can attach this to any variable holding an array and it will return the number of items inside.

let newYearsResolutions = ['Rappel into a cave', 'Take a falconry class'];

console.log(newYearsResolutions.length);
// Output: 2

In the example above, we log newYearsResolutions.length to the console. This code retrieves the length property of the newYearsResolutions array and logs it to the console. This array has two items, so 2 would be logged to the console.

Let's find the length of our newYearsResolutions``` array and log it to the console.

If what you have below is your answer:

console.log(newYearsResolutions.length);
// Output: 3

Good job!

push Method

JavaScript has built in methods for arrays that help us do common tasks. Let's learn some of them.

First, .push() allows us to add items to the end of an array. Here is an example of how this is used:

let newYearsResolutions = ['item 0', 'item 1', 'item 2'];

newYearsResolutions.push('item 3', 'item 4');

The method .push() would make the newYearsResolutions array look like:

['item 0', 'item 1', 'item 2', 'item 3', 'item 4'];

So, how does .push() work?

  1. It connects to newYearsResolutions with a period.
  2. Then we call it like a function. That's because .push() is a function and one that JavaScript allows us to use right on an array.

Another array method, .pop(), is similar to .push(). This method removes the last item of an array.

let newYearsResolutions = ['item 0', 'item 1', 'item 2'];

newYearsResolutions.pop();

console.log(newYearsResolutions); 
// Output: [ 'item 0', 'item 1' ]

In the example above, calling .pop() on the newYearsResolutions array removed item 2 from the end.

Go ahead and add two more items to your newYearsResolutions array using .push().

It should look something like this:

newYearsResolutions.push('improve my JavaScript skills','increase list of clients');

Now, use console.log to print your newYearsResolutions array to make sure your items were added.

newYearsResolutions.push('improve my JavaScript skills','increase list of clients');
console.log(newYearsResolutions);

// Output: [ 'mentor more students',
  // 'Learn a new language',
  // 'learn more business skills',
  // 'improve my JavaScript skills',
  // 'increase list of clients' ]

Now, use the .pop() method to remove the last element from your array.

Log newYearsResolutions to the console to make sure it worked.

newYearsResolutions.pop();
console.log(newYearsResolutions);

// Output: [ 'mentor more students',
  // 'Learn a new language',
  // 'learn more business skills',
  // 'improve my JavaScript skills' ]

If you got something similar to the above, great job!

More Array Methods

There are many more array methods than just .push() and .pop(). You can read about all of the array methods that exist on the Mozilla Developer Network (MDN) documentation.

.pop() and .push() modify the array on which they're called. However, there are some array methods that don't modify the array. Be sure to check MDN to understand the behavior of the method you are using.

Some methods that JavaScript developers use frequently are .join(), .slice(), .splice(), .shift(), .unshift(), and .concat() amongst many others.

Below, we will explore some methods that we have not learned yet. We will use these methods to edit a grocery list. As you complete the steps, you can consult the MDN documentation to learn what each method does!

Create an array called groceryList.

let groceryList = ['orange juice', 'bananas', 'coffee beans', 'brown rice', 'pasta', 'coconut oil', 'plantains'];

Use the .shift() method to remove the first item from the array groceryList.

Log the new groceryList to the console.

You should have gotten what you see below:

groceryList.shift();
console.log(groceryList);

Now use the .unshift() method to add 'popcorn' to the beginning of your grocery list.

Log the new grocery list to the console.

You should have what you see below:

groceryList.unshift('popcorn');
console.log(groceryList);

You're in a hurry so you decide to ask a friend to help you with your grocery shopping. You want him to pick up the bananas, coffee beans, and brown rice.

Use .slice() to provide him with a list of these three things.

Log this part of the list to the console. Unlike the two previous checkpoints, you should do both of these steps in one line.

Did you find this one challenging? That's okay, if you don't know how .slice() works, you would not get this on the first try. Here is the answer below:

console.log(groceryList.slice(1, 4));

Arrays with let and const

You may recall that you can declare variables with both the let and const keywords. Variables declared with let can be reassigned.

Variables that are assigned with const cannot be reassigned. However, arrays that are declared with const remain mutable, or changeable.

This means that we can change the contents of an array, but cannot reassign the variable name to a new array or other data type.

The instructions below will illustrate this more clearly. Pay close attention to the similiarities and differences between the condiments array and the utensils array as you complete the steps.

Look at the following arrays below:

let condiments = ['Ketchup', 'Mustard', 'Soy Sauce', 'Sriracha'];

const utensils = ['Fork', 'Knife', 'Chopsticks', 'Spork'];

Now add your favorite condiment to the condiments array using .push().

Log the updated array to the console.

Your code should look similar to what I have here below:

condiments.push('garam masala');
console.log(condiments);
// Output: ['garam masala']

One of a computer's greatest abilities is to repeat a task multiple times. Loops let us tell the computer to loop over a block of code so that we don't have to write out the same process over and over.

Loops are especially useful when we have an array where we'd like to do something to each of its items, like logging each item to the console.

There are two kinds of loops we will learn in this lesson:

  1. for loops, which let us loop a block of code a known amount of times.
  2. while loops, which let us loop a block of code an unknown amount of times.

Check out the code below:

let cookies = ['chocolate chip', 'raisin', 'macadamia nut', 'sugar'];

for (let i = 0; i<cookies.length; i++) {
  console.log('I would love to eat a ' + cookies[i] + ' cookie right now!');
}

What do you think will happen when we execute the code in the code editor? When you think you know, run this code in your favorite code editor and see what happens!

Looping Manually

Before we jump into writing a loop, let's write the output of a loop, so that we can better understand the benefits of writing them.

Write an array and set it equal to a variable named vacationSpots. Inside of this array, list three places you'd like to visit.

let vacationSpots = ['Cuyahoga Falls','Shenandoah Valley','Smoky Mountain'];

Next, console.log() each item in vacationSpots on a separate line. To do this, list out each item using property access.

console.log(vacationSpots[0]);
console.log(vacationSpots[1]);
console.log(vacationSpots[2]);
// Output: Cuyahoga Falls
// Shenandoah Valley
// Smoky Mountain

Nice work! I hope the instructions wasn't too confusing. Imagine if our vacation list had 100 places on it. Logging each item to the console by hand would be an extremely tedious task!

Let's make this more efficient with a for loop.

for Loops

Instead of writing out the same code over and over, let’s make the computer loop through our array for us. We can do this with for loops.

The syntax looks like this:

let animals = ["Grizzly Bear", "Sloth", "Sea Lion"];

for (let animalIndex = 0; animalIndex < animals.length; animalIndex++) {
  console.log(animals[animalIndex]);
}

The output would be the following:

Grizzly Bear Sloth Sea Lion

Since this syntax is a little complicated, let's break it into four parts:

  1. Within the for loop's parentheses, the start condition is let animalIndex = 0, which means the loop will start counting at 0. animalIndex is called an iterator variable and it is a good practice to give this variable a descriptive name.
  2. The stop condition is animalIndex < animals.length, which means the loop will run as long as animalIndex is less than the length of the animals array. When animalIndex is equal to the length of the animals array, the loop will stop executing.
  3. The iterator is animalIndex++. This means that after each loop, animalIndex will increase by 1. Finally, the code block is inside of the { and } curly braces. The block will execute each loop until the program reaches the stop condition.

The secret to loops is that animalIndex, the variable we created inside the for loop's parentheses, is equal to a number. To be more clear, the first loop, animalIndex will equal 0, the second loop, animalIndex will equal 1, and the third loop, animalIndex will equal 2.

Loops make it possible to write animals[0], animals[1], animals[2] programmatically instead of by hand. We can write a for loop and replace the hard-coded number with the variable animalIndex, like this: animals[animalIndex].

Let's replace your current code with a loop. Delete the three console.log() statements from the previous exercise.

Write a for loop that loops through your vacationSpots array.

Use vacationSpotIndex as your iterator variable.

Inside the block of the for loop, use console.log() to print each item in the vacationSpots array.

Ready? Your code should look like this:

let vacationSpots = ['Cuyahoga Falls','Shenandoah Valley','Smoky Mountain'];

for (let vacationSpotIndex = 0; vacationSpotIndex < vacationSpots.length; vacationSpotIndex++ ) {
  console.log(vacationSpots[vacationSpotIndex]);
}
// Output: Cuyahoga Falls
// Shenandoah Valley
// Smoky Mountain

Way to go! Now, add text to the console.log() statement, like this:

let vacationSpots = ['Cuyahoga Falls','Shenandoah Valley','Smoky Mountain'];

for (let vacationSpotIndex = 0; vacationSpotIndex < vacationSpots.length; vacationSpotIndex++ ) {
  console.log(vacationSpots[vacationSpotIndex]);
  console.log('I would love to visit ' + 		vacationSpots[vacationSpotIndex]);
}
// Output: Cuyahoga Falls
// I would love to visit Cuyahoga Falls
// Shenandoah Valley
// I would love to visit Shenandoah Valley
// Smoky Mountain
// I would love to visit Smoky Mountain

for Loops, Backwards

If we can make a for loop run forwards through an array, can we make it run backward through one? Of course!

We can make our loop run backward by modifying the start, stop, and iterator conditions.

To do this, we'll need to edit the code between the for loop's parentheses:

  1. The start condition should set vacationSpotIndex to the length of the array.
  2. The loop should stop running when vacationSpotIndex is less than 0.
  3. The iterator should subtract 1 each time, which is the purpose of vacationSpotIndex--.

We need to make three changes to our for loop:

Edit the start condition to set vacationSpotIndex equal to the length of the vacationSpots array.

Then, set the stop condition to when vacationSpotIndex is greater than or equal to 0.

Finally, change vacationSpotIndex++ to vacationSpotIndex-- to subtract 1 from the iterator variable each loop.

Now if we leave the code as instructed above, we will print I would love to visit undefined.

This happened because the length of vacationSpots is 3 so the loop attempted to print vacationSpots[3] which does not exist.

Because arrays start counting at 0, the start condition needs to be the length of the vacationSpots array minus 1, like this:

let vacationSpots = ['Cuyahoga Falls','Shenandoah Valley','Smoky Mountain'];

for (let vacationSpotIndex = vacationSpots.length - 1; vacationSpotIndex >= 0; vacationSpotIndex-- ) {
  console.log(vacationSpots[vacationSpotIndex]);
  console.log('I would love to visit ' + 		vacationSpots[vacationSpotIndex]);
}
// Output:  Smoky Mountain
// I would love to visit Smoky Mountain
// Shenandoah Valley
// I would love to visit Shenandoah Valley
// Cuyahoga Falls
// I would love to visit Cuyahoga Falls

Nested for Loops

Let's say that you and a friend would like to go on vacation together. You've both made arrays of your favorite places and you want to compare to see if any of them match. This is a job for loops!

The big idea is that we can run a for loop inside another for loop to compare the items in two arrays.

Every time the outer for loop runs once, the inner for loop will run completely.

These are called nested for loops and we can use them to check to see if any of your vacation spots match your friend's spots.

See the example below for proper formatting of nested for loops.

for (let i = 0; i < myArray.length; i++) {
  for (let j = 0; j < yourArray.length; j++) {
    //Code To Run
   }
 }

Note that in the example above, we used i and j as the iterator variables to make the structure of the code easier to see, but it is a better practice to use descriptive variable names.

while Loops

Awesome job! for loops are great, but they have a limitation: you have to know how many times you want the loop to run. What if you want a loop to execute an unknown or variable number of times instead?

For example, if we have a deck of cards and we want to flip cards (loop a card flipping function) until we get a Spade, how could we write that in JavaScript?

That's the purpose of the while loop. It looks similar to a for loop. See the example below.

while (condition) {
  // code block that loops until condition is false
}
  1. The loop begins with the keyword while.
  2. Inside the parentheses, we write a condition. As long as the condition evaluates to true, the block of code will loop.
  3. Inside the code block, we can write any code we'd like to loop.

Now go ahead and create an array of playing cards, then create a variable named currentCard and set it equal to 'Spade'.

This variable will hold the name of the card we just flipped. We are using 'Spade' as the first card.

Next, create a while loop. The condition should check if the currentCard is NOT a 'Spade'.

In the block of the while loop that you wrote in the previous step, log the value of currentCard to the console. Because the while loop only runs if the card is NOT a Spade, the value of currentCard will only be logged to the console if it is not 'Spade'.

Below the console.log() statement, add this code:

currentCard = cards[Math.floor(Math.random() * 4)];

It should all look like this:

let cards = ['Diamond', 'Spade', 'Heart', 'Club'];
let currentCard = 'Spade';

while (currentCard !== 'Spade') {
  console.log(currentCard);
  currentCard = cards[Math.floor(Math.random() * 4)];
}

This code will generate a random number between 0 and 3, the range of indices of the cards array, and reassign currentCard to a new card from that array.

Infinite Loops

Loops are a useful tool for improving the functionality of our programs. However, loops can also cause us problems if we aren't careful.

Both for loops and while loops need explicit instructions on when to terminate. Infinite loops are more common in while loops because they don't have an iterator built into their syntax. When writing a while loop, be sure to write the code that will guarantee the condition will eventually be met.

for loops require a start condition, a stop condition, and an iterator. The iterator should bring the loop from the start condition to the stop condition.

for (let i = 0; i < array.length; i--) {
   //some code
}
  1. The loop begins with i = 0.
  2. After one iteration through the loop, i is equal to -1. This is because i begins at 0 and 1 is subtracted from i each loop.

Do you see the problem? i is decreasing each time. It will never equal the length of the array. This code will execute forever.

for (let i = 0; i < array.length; i++) {
   //some code
}

I changed the iterator to i++ which means i will eventually equal the length of the array. We have eliminated the infinite loop!

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment