2. JS Making Decisions Public

2. JS Making Decisions

Kostas Diakogiannis
Course by Kostas Diakogiannis, updated more than 1 year ago Contributors

Description

Making decisions with conditional statements.

Module Information

No tags specified

Context

Course's Objectives At the end of the course each participant should have learned: 1. What a boolean data type is, which values it accepts and why it is useful? 2. How to perform decision making using boolean values. Additionally how many different ways exist to make a decision and which one is appropriate in any situation. 3. How to write if...else statements,  switch cases and ternary operators, and most importantly what are the differences between them and when to use one in favor of the other? 4. Make comparisons by using comparison operators (>, <, ==, ===, !=, >=, <=) and guess what the outcome of these operations is. 5. Use comparison operators along decision making statements in order to execute a part of code selectively. 6. Use logical operators to group comparisons together and make complex decision making. 7. What OR, AND, and NOT operators solely do. How do they combine together? 8. What is the order of precedence between logical operators?
Show less
No tags specified

Context

Making Decisions in JS Take a closer look to the interactive map above.  Let's assume that you find yourself in front of a hotel and you want to spend the night there. You have a specific amount of money in your wallet (let's say 50$ for the sake of our example). You have no idea if this money is enough to get you a fine bed for the night  into the hotel. So you decide to go in and ask at the reception desk.  The first thing you want to ask, is the absolutely essential. If your money is enough to get the cheapest room here or not. This is the first question you want to make, because if the answer is negative, then there is no reason to spend more time in the hotel. You need to find another place. If your money is enough to buy the cheapest room, then you can also explore further for additional info, in order to find out if you have also enough money for something better. For example, how much does it cost an upgraded room? If you can't afford it, then you stay with the cheapest room. Otherwise you can upgrade to the better and more comfortable room.   Regardless of that, if you can pay the cheapest room, then you can optionally go for a suite. The only prerequisite is that you are a  VIP person (and you can pay the cheapest room at least). Then you get an automatic upgrade to one of the four color suites of the hotel. Depending on your favorite color you get either the red, blue or green suite.   If none of these is your favorite color then you get the Grey suite. Although this is a real world problem, we can implement solutions on problems like that in programming, by making decisions. Decisions as we would make them in real life. What we actually did, is that we made comparisons. We compared our money with several prices. Based on the outcome of these comparisons, we made different decisions. Let's learn how to implement solutions for such problems by writing code!
Show less
No tags specified

Context

How to make Decisions in JS. The first way is by creating if statements. By if statements you can check if a specific condition is true or false. Then you can specify and define a block of code that will be executed only when the condition is true, and another block of code for when the condition is false. Once you understand this you can create your own decisions based on the outcome of a condition you are checking. But how do i create expressions that evaluate either to true or to false? See next chapter.
Show less
No tags specified

Context

The if...else statement If statements are a perfect example on how to implement solutions that apply to our previous hotel problem. Instead of running a full program from top to bottom (from line 1 to the end of it) unquestioningly, we can define blocks of code that will run conditionally, and only when the condition evaluates to true. As shown above, the way to do this is by typing an if keyword followed by parentheses and then by curly braces. Whatever lies inside the curly braces will be executed ONLY if the expression inside the parentheses evaluates to true! If not, then the whole block will be ignored.  Additionally you can define another block of code that will execute in case the first block condition evaluates to false. As an alternative in other words. This is done by defining an else case and then the block of code that will run in such cases. This else statement is connected to the if statement, that means ONLY ONE of these blocks will be executed at the end of the day. The most important part to know, is that the expression inside the parentheses that follow an if statement must return either a 'truthy' or a 'falsy' value. But what are these values and how can we access them?
Show less
No tags specified

Context

Boolean Values   Boolean values accept only true and false values.. They express if a state of a variable is truthy or falsy. They are one of JS seven data types. They can be stored to variables exactly as numbers or strings. Comparison operators and logical operators (see later) return always boolean values as result to their expressions.  Thus when comparing we can identify if the comparison is true or false and we can make decisions upon that. Let's see how!
Show less
No tags specified

Context

Making Comparisons Comparing two different values is part of real everyday life. We compare prices from different stores, and then we decided which price is closest to our interest to chose. That means, that even when this happens in milliseconds, we compare things, and based on the outcome of these things we decide if we will do something or not. This concept doesn't change much to programming and in our case we will see how to make comparisons by using JavaScript comparison operators.   Comparison operators allow us to compare two different parts. This could vary and there are many types of operators that we can pick. From checking equality, inequality, if something is greater or lower than it's counterpart and many more. All JS comparison operators are: > Checking if the expression on the left is bigger than the one on the right < Checking if the expression on the left is smaller than the one on the right >= Checking if the expression on the left is bigger or equal than the one on the right <= Checking if the expression on the left is less than or equal than the one on the right != Checking if the expression on the left is not equal to the one on the right == Checking if the expression on the left is equal than the one on the right === Checking if the expression on the left is equal than the one on the right. Checks type also. The most important thing to understand and keep from this is that the data type that is returned from each and one of those operations is a boolean! That means that we inject the whole comparison operation inside an if statement's parentheses. Since whatever is inside the parentheses evaluates to true or to false, we will execute the following block of code conditionally.
Show less
No tags specified

Context

Nested if statements   What if i want to check further conditions inside conditions? For example i want to check for a condition if the weather is bad. In case this is false i decide to go out with my t-shirt. What if this is true? Then i need to check further if we are talking about rain (so i would take an umbrella, or if it snows , then i will go skiing!). It is also possible to implement if statements that are lying inside other if statements. As the picture shows above, first i check if i have enough money to buy a single room to spend the night. If this is true, then and ONLY then i can explore further and check if i have 100$ more than the cheapest room. In such case, i can go possibly to a better hotel, or for example upgrade for a better room. If not, then probably i will take the cheapest room.  All this upgrade plan will happen ONLY if i have enough money to take the cheapest room, then i can ask further to make myself more comfortable etc. But if i don't have the money even for that, then i will have to keep looking elsewhere.
Show less
No tags specified

Context

Logical Operators   Logical operators are used in order to group boolean values or boolean expressions together and make decisions based on, if all of them, one of them  or none is true. There are 3 Logical operators and all of them return boolean values: The AND  operator: &&. That checks if both conditions are true and evaluates to true. If only one of the conditions that are being checked is false then the whole logical operation evaluates to false. For example i am going to buy myself an ice cream ONLY when i have enough money for it (so the money in my wallet is bigger number than the price of the ice cream) AND if the temperature is more than 25 degrees! If one of these conditions evaluate to false then the whole condition is false. BOTH have to be true in order to buy the ice cream. We group this condition with the AND (&&) operator. The OR operator: ||. Checks if one condition of the group is true. If so it evaluates the whole operation to true. Either the one or the other one is enough to evaluate to true. The NOT operator:  ! Checks if something is not true. (see comparison operators also).
Show less
No tags specified

Context

Checking multiple cases What if we want to check more than one cases. Take a look at the sample code above. There we have defined a variable that represents the favorite color of a user (cyan for now), and based on that we want to print to the console a relevant band.  So if user's favorite color is red, then we give back 'Red Hot Chilli Peppers'. If is green, we print 'Green Day' if purple, 'Deep Purple' Otherwise if none of that we give back 'Black Sabbath'. Each if (or else if) statements is checked sequentially, the first statement's condition that evaluates to true, executes the following block. Then ALL the following blocks, are ignored!
Show less
No tags specified

Context

D1 - The FizzBuzz Problem Write  a single script that stores a single integer into a variable. This integer can be anything between 1 and 100.  Then write a script that prints different things to the console based on the number provided. Specifically: If the number is multiple of 3 (3, 6, 9 etc) print 'Fizz' to the console. If the number is multiple of 5 (5, 10 etc) print 'Buzz' If it's multiple of both 3 and 5 (15, 30, 45) then print 'FizzBuzz' Otherwise print the number itself. Test that your script works by changing the number regularly. Check all cases work properly.
Show less
No tags specified

Context

Switch-Cases Switch cases are another way to implement decision making in JavaScript in a little bit different way than if-else statements. To be completely accurate is just a syntactic sugar. That means that logic-wise nothing changes fundamentally, JavaScript just provides us with something that looks more elegant syntax-wisely. But when is more appropriate to use a switch-case syntax in favor of a if...else statements? The answer is when you want to check multiple if statements, and you check the same variable over and over again if it contains a specific value. In our case we have rewritten the bands based on favorite color example, in a switch-case mode.  Note the break keyword. This prevents further execution when a condition is met. That means if your favorite color is green, then the corresponding code is executed 'Green Day' and stops there. If the break keyword inside the case is omitted, then we will also go further and execute the purple case! The default case is not mandatory, but it acts like a backup code that will be executed if all previous cases evaluate to false. The benefit is a cleaner and easier to read structure that enhances debugging experience. Curly braces is not needed and the programmer is allowed inside a switch-case block to write code that looks similar "python-ruby" style.
Show less
No tags specified

Context

D2 - Ice Cream exercise   Suppose that you are working by an ice cream shop, that has waffles where you can put from 1 up to 5 balls. Write a program that reads the number of ice creams balls the customer wants and stores it to a variable. Then calculates the cost accordingly. The prices are the following: 1 ball: 1$ 2 balls: 1,8$ 3 balls: 2,5$ 4 balls: 3$ 5 balls: 3,30$ If no balls is specified by the customer the default should be the price for 2 balls. Print the correct price to the console at the end.
Show less
No tags specified

Context

D3 - Lottery number re-order exercise   Your colleague was working last night on a task that code-wise has been almost finished. The problem is that he apparently got drunk at some point and messed up with the order of execution of the program.  Without changing the code, except only for putting the necessary curly braces to find the right code blocks order execution, reorder the lines shown in the photo above in order to achieve the following result. The program accepts 3 inputs and reads them. The first is a random lottery  number from 1 to 1000 (in this case will be a give number) that a customer buys from you. Feel free to define this number manually. The second is the jackpot winning prize that is 1000$. And a third input is the standard winnings. The latter acts like a basis. The basis is 10$ but it can be much more or nothing depending on the area the random number belongs to (for now give a value of 10$ there). In case the number the customer bought is from 1 to 499 the earnings become from 10$ to 0. So if the customer gets a number withing this range, he wins nothing. If the number the customer bought, is between 500 and 699 or between 800 and 899 then he wins the basis twice. In case he picks a number that belongs to 700 area (700-799) he wins the basis 10 times! Especially the numbers 776, 777, 778 they produce another winning pot. 777 gives him the jackpot. 776 gives him half of the jackpot and 778 gives him the 1/5 of the jackpot. In any other number circumstance (900 and more or so)   the customer takes the basis 5 times. Reorder the exercise lines accordingly, add the curly braces where missing, and don't forget to print to console a descriptive message that includes the winnings of the customer.
Show less
No tags specified

Context

D4 - Selling smartphones exercise   Suppose you sell smartphones to customers. Write a program with multiple conditions as before in order to sell a smartphone to a customer who is interested. Smartphone's price is 300$ and your cashier balance is 0 at the beginning. Also the customer should know that you sell some accessories with the smartphone. Headphones price is 50$, and cover for the smartphone 20$ each. If the customer is not interested on buying anything then your cashier remains 0.  If he interests on buying only the smartphone then add the price of the smartphone to your cashier. If the customer also wants to buy headphones, he gets 10% discount of the total price (headphones and smartphone together). Update your cashier (total sales) accordingly. In case the customer wants headphones and cover the discount is 15%.  If the customer wants only a cover, discount is 5% unless he chooses one of these 3 colors: green (7% discount), pink (12% discount) or orange (15% discount). Update your cashier accordingly then. Selling only accessories without a smartphone is not possible. Print your cashier after the sale so your boss knows exactly how much did you manage to sell to this customer. p.s. Before you begin create a map on paper to help you organize and articulate your thoughts.
Show less
No tags specified

Context

The ternary operator The ternary operator is used exactly the way an if ... else statement is used with the exception that no multiple if conditions are allowed.  There is only one condition that is being checked and this evaluates to either true or false.  Based on the outcome we execute a different part of code.  It an error prone syntax and beginners need to be careful with it, but when used correctly is very concise, easy to read and save work from syntax mess. The syntax is:  condition ? code to be executed in case of true : code to be executed in case of false ex. 10 > 5 ? console.log('yes it is bigger') : console.log('nope it is not') // prints 'Yes it is bigger' ex. 10 < 5 ? console.log('yes it is bigger') : console.log('nope it is not') // prints 'nope it is not' Mostly it is used instead of single if...else statements when there is only one condition to be checked.
Show less
No tags specified

Context

D5 - Practice Makes Perfect   1. Write a program that accepts a number, and print to the console if its negative, positive or 0. 2. Write a program that reads a number and return it's opposite. If 5 returns -5. If -12 returns 12 etc. Do it without using the native Math object, only with if statements (or even without). 3. Write a program that accepts 5 inputs as numbers. Calculate the sum and the average of them. 4. Write a program that accepts 3 numbers and prints the biggest of them. 5. Store a year in a variable and check if this year is a leap year (366 days) given that leap years  are 2016, 2012, 2008, 2004, 2000 etc. Print to the console 'yes' or 'no' accordingly.
Show less
No tags specified
What comes next? 1. Perform repetitive tasks by using the loop concept. 2. What is the while loop and how it can be used? 3. What is the for loop and  how it can be used? 4. What are the differences between a for and a while loop and when is more appropriate to use the one in favor of the other? 5. What does the 'break' keyword in loops do? 6. What does the 'continue' keyword do? 7. How to create nested loops and what kind of problems they solve?
Show less
Show full summary Hide full summary