Essential Question: How can I create variables in JavaScript?
Mastery Objectives:
SWBAT create constants in JavaScript.
SWBAT create variables.
Do Now: Write a JavaScript function to print the contents of the current window.
Important Points:
const stands for constant. Assigning a variable as a constant means you can't change it.
let assigns a value to a variable and allows you to reassign a value.
If you don't assign a value to a variable when you create it, it will be declared undefined, meaning it has no datatype. But assigning a string or number value, lets the computer know that it is a string or a number.
Directions: Type out the following code and view the results.
Use the += mathematical assignment operator to increase the value stored in levelUp by 5.
Use the -= mathematical assignment operator to decrease the value stored in powerLevel by 100.
Use the *= mathematical assignment operator to multiply the value stored in multiplyMe by 11.
Use the /= mathematical assignment operator to divide the value stored in quarterMe by 4.
Using the increment operator, increase the value of gainedDollar.
Using the decrement operator, decrease the value of lostDollar.
Create a variable named favoriteAnimal and set it equal to your favorite animal.
Use console.log() to print 'My favorite animal: ANIMAL' to the console.
Use string concatenation so that ANIMAL is replaced with the value in your favoriteAnimal variable.
Important Point:
We can insert, or interpolate, variables into strings using template literals. Check out the above example where a template literal is used to log strings together: a template literal is wrapped by backticks ` (this key is usually located on the top of your keyboard, left of the 1 key).
Directions: Type out the following and view the results:
Create a variable called myName and assign it your name.
Create a variable called myCity and assign it your favorite city’s name.
Use a single template literal to interpolate your variables into the sentence below. Use console.log() to print your sentence to the console in the following format:
My name is NAME. My favorite city is CITY.
Replace NAME and CITY in the string above by interpolating the values saved to myName and myCity.
Use console.log() to print the typeof newVariable.
let newVariable = 'Playing around with typeof.';
Great, now let’s check what happens if we reassign the variable. Below the console.log() statement, reassign newVariable to 1.
Since you assigned this new value to newVariable, it has a new type! On the line below your reassignment, use console.log() to print typeof newVariable again.