Introduction to JavaScript​ 2

1/8 VARIABLES

Variables

Programmers use variables to write code that is easy to understand and repurpose.

Imagine you’re writing a weather app. Your thermometer outside reports the temperature in Celsius, but your goal is to record the temperature in Fahrenheit.

You write a program that takes a temperature of 15 degrees Celsius and calculates the temperature in Fahrenheit.

Once you’ve done this though, you see the temperature now reads 16 degrees Celsius. To find Fahrenheit again, you’d need to write a whole new program to convert 16 degrees Celsius to Fahrenheit.

That’s where variables come in. Variables allow us to assign data to a word and use the word to reference the data. If the data changes (like degrees Celsius) we can replace the variable’s value instead of re-writing the program.

In this lesson you will learn about two ways to declare variables: let and const.

 

Instructions

  1. Run your code.
    Was anything printed to the console?

    // This line of code sets the variable location to the string New York City

    const location = ‘New York City’;

    // This line of code sets the variable latitude to the number 40.7

    let latitude = 40.7;

    // This line of code sets the variable inNorthernHemisphere to true

    let inNorthernHemisphere = true;

  2. Add the following lines of code to the bottom of app.js:

console.log(location);

console.log(latitude);

console.log(inNorthernHemisphere);

 

Run your code and take a look at the console.
Are the results what you expected?

 

2/8 VARIABLES

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 example above:

  • const, short for constant, is a JavaScript keyword that creates a new variable with a value that cannot change.
  • 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.
  • = is the assignment operator. It assigns the value (‘Arya’) to the variable (myName).
  • ‘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, on line 1 the myAge variable is set to 11. Below that, console.log() is used to print 11 to the console.

 

Instructions

  1. Create a constant variable named entree and set it to equal to the string ‘Enchiladas’.
    Use the const keyword to make a variable.
  2. Now, under the entree variable, create a constant variable named price that saves the number 12.
    Use const to create a variable named price and save the number 12 to it.
  3. Under the price variable, use console.log() to print the value saved to entree.
    On the following line, use console.log() to print the value saved to price.
  4. Copy and paste the following code to the bottom of your program.

entree = ‘Tacos’;

This code throws the following error when you run your code:

TypeError: Assignment to constant variable.

We’ll discuss what’s going on here in the next exercise.

3/8 VARIABLES

Create a Variable: let

In the final task of the previous exercise you received the following error:

 

TypeError: Assignment to constant variable.

JavaScript threw an error because you assigned a new value to a constant variable. 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.

 

Instructions

 

  1. Create a let variable called changeMe and set it equal to the Boolean true.
    In the example below, the variable thisVariable is set to the value false.
    let thisVariable = false;
  2. Set the changeMe variable to the boolean false. Log the value saved to changeMe to the console.

4/8 VARIABLES

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, we created the variable whatAmI without any value assigned to it. JavaScript creates the variable and sets it equal to the value undefined.

 

Instructions

 

  1. Create a variable named notDefined, but don’t set it equal to anything.
    Log the result to the console.
    The example below shows how you create a variable without assigning it a value.
    let noValue;
  2. Create an undefined variable named valueless.
    Log the result to the console.

 

5/8 VARIABLES

Mathematical Assignment Operators

In this exercise, 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, we 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:

  • 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.
  • The last two operators are the increment (++) and decrement (–) operators. These operators are responsible for increasing and decreasing a number variable by one, respectively.

 

Instructions

  1. Use a mathematical assignment operator to add 16 to the value saved to molecule.
    Use the += operator as follows:

let water = 18;

water += 16; // atomic mass of hydrogen peroxide

  1. Use a mathematical assignment operator to assign particle the value of itself multiplied by 6.02.
    Use the *= operator as follows:

let water = 18;

water *= 6.02; // number of particles in a mole of water x10^23

 

  1. Use the increment operator to increase the value saved to assay by 1.

6/8 VARIABLES

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.

 

Instructions

 

  1. Create a variable named favoriteAnimal and set it equal to your favorite animal.
    Use the let keyword to create favoriteAnimal.
  2. Use console.log to print: ‘My favorite animal: Koala’, but replace ‘Koala’ with your favoriteAnimal variable.

7/8 VARIABLES

String Interpolation II

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

  • 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).
  • 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.’

 

In the example above, the backticks (`) wrap the entire string. The variable (myPet) is inserted using ${}. The resulting string is:

I own a pet armadillo.

 

Instructions

 

  1. Create a variable called myName and assign it your name.
  2. Create a variable called myCity, and assign it your favorite city’s name.
  3. 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.

8/8 VARIABLES

Review Variables

Nice work! This lesson covered a lot of foundational skills that you will often use in your future programming endeavors.

Let’s review what we learned:

 

    • Variables hold reusable data in a program.
    • JavaScript will throw an error if you try to reassign const variables.
    • You can reassign variables that you create with the let keyword.
    • Unset variables store the primitive data type undefined.
    • Mathematical assignment operators make it easy to calculate a new value and assign it to the same variable.
    • The + operator is used to interpolate (combine) multiple strings.
    • In JavaScript ES6, backticks (`) and ${} are used to interpolate values into a string.
 

Sé el primero en comentar

Deja una respuesta