M1D6: JavaScript – Advanced Use of Operators

Task 1: Using the logical && operator

You are coding an RPG game, where each character has certain skill levels based on the value saved in their score.

  1. Create a variable named score and set it to 8
  2. Use console.log() that includes the string “Mid-level skills:” and compares the score variable to above 0 and below 10 using the && operator

The expected output in the console should be: “Mid-level skills: true”.

var score = 8
console.log("Mid-level skills:", score > 0 && score < 10)

Task 2: Using the logical || operator

Imagine you are coding a video game. Currently, you’re about to code some snippets related to the game over condition.

You need to code a new variable named timeRemaining and set it to 0. You also need to code a new variable named energy and set it to 10.

Next, you should write a piece of code that could be used to determine if the game is over, based on whether either the value of the timeRemaining variable is 0 or the value of the energy variable is 0.

Complete the task using the following steps:

  1. Declare the variable timeRemaining, and assign the value of 0 to it.
  2. Declare the variable energy, and assign the value of 10 to it.
  3. Console log the following parameters: “Game over: “, and timeRemaining == 0 || energy == 0

Note that the expected output in the console should be: “Game over: true”.

var timeRemaining = 0
var energy = 0

console.log("Game over: ", timeRemaining == 0 || energy == 0)

Task 3: Using the modulus operator, %, to test if a given number is odd

You need to code a small program that takes a number and determines if it’s an even number (like 2, 4, 6, 8, 10).

To achieve this task, you need to declare six variables, as follows:

  1. The first variable, named num1, should be assigned a number value of 2.
  2. The second variable, named num2, should be assigned a number value of 5.
  3. The third variable, named test1, should be assigned the calculation of num1 % 2. Note: executing this code will return a number.
  4. The fourth variable, named test2, should be assigned the calculation of num2 % 2. Note: executing this code will also return a number.
  5. The fifth variable, named result1, should be assigned the result of comparing if the number stored in the test1 variable is not equal to 0, in other words, this: test1 == 0.
  6. The sixth variable, named result2, should be assigned the result of comparing if the number stored in the test2 variable is not equal to 0, in other words, test2 == 0.

Run console log two times after you’ve set the variables:

  1. The first console log should have the following code between parentheses: “Is”, num1, “an even number?”, result1
  2. The second console log should have the following code between parentheses: “Is”, num2, “an even number?”, result2

Note: The output to the console should be as follows:

Is 2 an even number? true

Is 5 an even number? false

var num1 = 2
var num2 = 5
var test1 = num1 % 2
var test2 = num2 % 2
var result1 = test1 == 0
var result2 = test2 == 0

console.log("Is", num1, "an even number?", result1)
console.log("Is", num2, "an even number?", result2)

Task 4: Add numbers using the + operator

Console log the result of adding two numbers, 5 and 10, using the + operator.

Note: This task should be completed on a single line of code. The output in the console should be 15.

console.log(5 + 10);

Task 5: Concatenate numbers and strings using the + operator

Code three variables:

  1. The first variable should be a string with the following value: “Now in “. Name the variable now.
  2. The second variable should be a number with the value: 3. Name the variable three.
  3. The third variable should a string with the following value: “D!”. Name the variable d.
  4. Console log the following code: now + three + d.

Note: The expected output should be: “Now in 3D!”.

var now = "Now in ";
var three = 3;
var d = "D!";

console.log(now + three + d);

Task 6: Use the += operator to accumulate values in a variable

Code a new variable and name it counter, assigning it to the value of 0.

On the next line, use the += operator to increase the value of counter by 5.

On the next line, use the += operator to increase the value of counter by 3.

On the fourth line, console log the value of the counter variable.

Note: The output value should be 8.

var counter = 0;
counter += 5;
counter += 3;

console.log(counter)

Additional resources

Here is a list of resources that may be helpful as you continue your learning journey.

These resources provide some more in-depth information on the topics covered in this module.

Mozilla Developer Network Expressions and Operators 

Mozilla Developer Network Operator Precedence and Associativity 

JavaScript Primitive Values 

ECMA262 Specification 

jQuery Official Website 

React Official Website 

StackOverflow Developer Survey 2021 Most Popular Technologies

Emojis

Writing Assignments

Examples of Condition:

Condition: Raining

Yes – Bring an umbrella

No – Don’t bring umbrella

Conditional Statements

if (condition == true) {
  execute code
}

IF Statement

  • checks a condition and will execute a code block if the condition is met or true. The condition criteria are essential here. The block of code will only get executed if the condition is evaluated to the Boolean value of true. You can use many types of comparison operators to evaluate the condition. These include operators such as equal to, greater than, less than, and not equal to.

Comparison Operators

== equal to
> greater than
< less than
!= not equal

IF ELSE Statement

if (condition == true) {
  //execute code
}
else {
  //execute code
}
  • This statement handles both outcomes of our conditional request using the else keyword. If a condition is true, do something. If it’s false, do something else. Recall, a driving test example. We can store the test result in a variable. Suppose the variable value is greater than 40. In that case, the true block is executed, and you output a message to the console telling the learner that they passed. Suppose the variable value is less than 40. In that case, the false block is executed, and you output a message to the console telling the learner that they did not pass.
var score = 10;

if (score > 40) {
  console.log("You passed!")
} 
else {
  console.log("You fail!")
}

Switch Statement

Switch statement works the same way with IF ELSE but better to be used if there are a lot of conditions, as less code are needed.

var place = "first";

switch(place) {
  case "first":
    console.log("Gold");
    break;
  case "second":
    console.log("Silver");
    break;
  case "third":
    console.log("Bronze");
    break;
  default:
    console.log("No medal");
}

Compared with ELSE IF

var place = "first";

if(place == "first") {
    console.log("Gold")
} else if (place == "second") {
    console.log("Silver")
} else if (place == "third") {
    console.log("Bronze")
} else {
    console.log("No medal")
}

Flow Control Statements – they control the flow of execution of your code, so that some code can be skipped, while other code can be executed.


Complete the following steps to create: Are You Old Enough?

  1. Declare a variable age using the var keyword and set it to the number 10.
  2. Add an if statement that checks if the value of the age variable is greater than or equal to the number 65. Inside the if block, console.log the sentence: “You get your income from your pension”.
  3. Add an “else if“, where you’ll check if the value of the age is less than 65 and greater than or equal to 18. Inside this “else if” block, type “console.log” and then “Each month you get a salary”.
  4. Add another “else if“, and this time check if the value of the age is under 18. Inside the “else if” block, “type console.log” and then “You get an allowance”.
  5. Add an “else” statement to capture any other value. Inside the block, type “console.log” and then “The value of the age variable is not numerical”.

Try adjusting the age and executing the program to see how it will affect the output.

var age = 10

if (age >= 65) {
    console.log("You get your income from your pension")
} else if (age < 65 && age >= 18) { // for && I have to specify the variable again, even if it's the same variable
    console.log("Each month you get a salary")
} else if (age < 18){
    console.log("You get an allowance")
} else {
    console.log("The value of the age variable is not numerical")
}

Code the days of the week program as a switch statement

  1. On the next line, define a new variable, name it day, and set its value to “Sunday”.
  2. Start coding a switch statement, passing the day variable as the expression to evaluate.
  3. Inside the switch, add cases for every day of the week, starting with ‘Monday’, and ending with ‘Sunday’. Make sure to use string values for days. Inside each case, for now, just add a console.log(‘Do something’), and add a break; on the line below.
  4. At the very bottom of the switch statement, add the default case and add a console.log(‘There is no such day’).
  5. Finally, update the console.log calls for each case, based on whatever activity you have on each of the days.
var day = "Sunday"

switch(day) {
    case "Monday":
        console.log("Swim today");
        break;
    case "Tuesday":
        console.log("DGroup today");
        break;
    case "Wednesday":
        console.log("Work");
        break;
    case "Thursday":
        console.log("Study day with kids");
        break;
    case "Friday":
        console.log("Work");
        break;
    case "Saturday":
        console.log("Work");
        break;
    case "Sunday":
        console.log("Go to church!");
        break;
    default: 
        console.log("There is no such day")

}

//I get confused with the : and ; from the switch statements. I also don't memorize this yet. I have to practice this more. 

Tips

  • If you need to make sure that multiple conditions are true in an if statement, you can do so using the && operator
  • In JavaScript, the correct syntax of the “greater than or equal to” operator is: >=.
  • Don’t forget to add a break at the very end of each case in a switch statement.

This entry was posted in Study Notes and tagged , . Bookmark the permalink.

Leave a Reply