Open variables.js in your text editor and solve the two challenges listed.
The problems are written as code comments //, which means they won't be executed by JavaScript. Make sure to run your code after each attempt to make sure you don't have any bugs!
Using console.log to print to the console
Declaring and initializing variables
Naming variables effectively
Assigning data of different data types to variables
Using template literals
Assigning updated values to variables
Using mathematical operators with variables
Increment and decrement
Understanding order of execution
You can print a single value to the console using console.log(). This can be useful for debugging your code, or simply displaying various things for a text-based application.
console.log("Hello World!");
console.log(5);
let x = 3;
console.log(x);
In terms of the relative precedence of each mathematical operator, JavaScript follows the same conventions you’re used to in algebra. Mathematical statements are evaluated using the standard order of operations, often referred to with the acronym PEMDAS ("Please Excuse My Dear Aunt Sally"): Parentheses, Exponents, Multiplication/Division, Addition/Subtraction.
Note that multiplication and division have the same precedence, so the order in which they are evaluated depends on where they appear in a given expression, read left-to-right. This same rule applies to addition and subtraction.
To demonstrate how JavaScript processes the order of operations, try this:
let num1 = 4 + 2 * 8;
let num2 = (4 + 2) * 8;
console.log(num1);
console.log(num2);
Before you hit run, what do you think will print?
Now, run the script, did you get it right?
JavaScript has two complementary division operators. The first one (/) does what you would normally expect: it simply divides the number on the left by the number on the right and gives you the quotient.
let num1 = 3 / 2;
console.log(num1);
The second operator (%) is called the modulus operator, or simply mod. Whereas the standard division operator (/) gives you the quotient of one number divided by another, the mod operator gives you the remainder.
For example, we know that 3 divided by 2 is 1.5. If we did remainder division, however, we would say 3 / 2 is 1 with a remainder of 1. The mod operator simply gives you the remainder.
Try it yourself:
let num1 = 3 % 2;
console.log(num1);
In a computer program, variables allow us to store and refer to data by name.
For example, if we are creating a video game where the player has a limited number of lives, we can store this data in a variable called lives. Each time the player dies, we subtract 1 from lives. When lives is 0, we end the game (Game Over!). This is just one of many ways variables can be useful in a program.
Variable declaration is when we create brand new variables in our programs. It starts with the keyword let followed by the variable name :
let num1;
This line of code declares a new variable called num1 but doesn't provide it any value. Therefore, the value of num1 is undefined.
You only need to use let when declaring a variable; after that, you can simply refer to the variable by its name.
Providing an initial value for a variable is called initialization.
The assignment operator can be used to initialize a variable on the same line where it is declared.
let num1 = 1;
Variables can also be initialized later in the script, so long as the variable was declared somewhere above the assignment statement:
let num1;
num1 = 1;
While programming, we frequently need to update a number variable by 1, whether that means adding or subtracting. For example, if I am programming a game where players have a number of lives, I might add 1 to the lives variable when players collect an extra life and subtract 1 when they die.
Adding 1 to a variable is called incrementing, and substracting 1 is called decrementing. Incrementing and decrementing happen so often in programming that many languages have even shorter shortcuts for each of these actions. Namely, to increment or decrement a variable, we attach ++ or -- to it, respectively.
This means that if we want to increment num1, there are three equivalent ways to do it:
num1 = num1 + 1;
num1 += 1;
num1++;
The same goes for decrementing num1:
num2 = num2 - 1;
num2 -= 1;
num2--;
Valid variable names consist of letters, digits, dollar signs, and underscores.
Variables should be written in lowerCamelCase unless they are constants, which should be written in all capital letters.
Camel case is the practice of writing phrases such that each word or abbreviation in the middle of the phrase begins with a capital letter, with no intervening spaces or punctuation. For example, "favorite ice cream" as a variable should be favoriteIceCream.
Variables should be short and meaningful. If someone else was reading your code, they would understand what the variable represents without explanation.
Variables can be assigned values by using the assignment operator (=)
In this example we assign values to num1 several times after it was initialized. Since JavaScript is run from top to bottom, each assignment statement overwrites the assignment above it.
let num1 = 1;
num1 = 3;
num1 = 58.2;
You can also assign variables to the current values of other variables. In the example below, we set num2 to the current value of num1. When num1 becomes 5, num2 remains 1, since it holds the value that num1 had at the time of assignment.
let num1 = 1;
let num2 = num1;
num1 = 5;
Below, what do you expect to happen to num1 and num2?
let num1 = 20;
let num2 = num1 + 5;
console.log(num1);
Why didn't num1 change?
JavaScript is temporarily holding onto whatever num1 + 5 evaluates to, and then storing it in the num2 variable. In other words, JavaScript is evaluating the expression on the right before it assigns it to the variable. Remember this one simple rule: evaluate, then store.
Here is another example of this same concept:
let num1 = 3;
let num2 = 10;
num1 = num1 + num2;
The code above follows the "evaluate, then store" rule:
Evaluate: The value of num1 at the time of assignment is 3. Adding 3 to num2 (10) yields 13.
Store: 13 is stored in num1, making its final value 13.
There are seven data types in JavaScript, but you only need to know four of them for now:
Number: any number value (1, -275, 3.1415)
String: any text value, wrapped within single (‘ ‘) or double (“ “) quotes. (“hi”, ‘I like computers’)
Boolean: values that are either true or false
Undefined: values that are not defined, but might be later
You can find out the data type of a value (or variable holding a value) by entering typeof before the value itself. This can be particularly useful when you want to verify that a variable holds a value of a specific data type.
let str = "Hello World!"
console.log(typeof str);
let iDontKnow;
console.log(typeof iDontKnow);
In JavaScript, strings can be enclosed with single or double quotes. Text can also be displayed across multiple lines by enclosing it with back-ticks ``. The back-tick key is located to the left of the 1 key on the keyboard.
This is useful for printing a block of text all at once, rather than line-by-line. For example, consider the code below:
console.log("The beginning of eternity,");
console.log("The end of time and space,");
console.log("The beginning of every end,");
console.log("And the end of every place.");
If you wrap the poem text within back-ticks, you can create a multi-line string, and simply print that one string with a single console.log() call.
console.log(`The beginning of eternity,
The end of time and space,
The beginning of every end,
And the end of every place.`);
Keep in mind that printed back-tick strings preserve the spacing/indentation that they have in the code.
Fun fact: Back-tick strings are called "template literals" in the actual JavaScript documentation. Google search that term to learn more. But you can just refer to them as "back-tick strings" or "multi-line strings", it's all the same.
Within back-tick strings, you can use placeholders to insert variable values at specific parts of the text. This is very handy, even when a back-tick string needs to appear on just one line.
Example:
let firstName = "April";
let lastName = "Alvarez";
console.log(`My name is ${firstName} ${lastName}. Nice to meet you!`);
Here are a few rules about placeholders:
A placeholder should have the same name as the variable it refers to, which should have been declared somewhere above where the placeholder appears in the code.
A placeholder should be contained within curly braces {}. Before the curly braces there should be a dollar sign $.