Monday, May 10, 2021

Javascript Practice 48: JS Hero - if...else

 
Question: 

Write a function addWithSurcharge that adds two amounts with surcharge. For each amount less than or equal to 10, the surcharge is 1. For each amount greater than 10, the surcharge is 2.

Example: addWithSurcharge(5, 15) should return 23.




Answer: 

function addWithSurcharge (a,b) {

if (a <= 10 && b <= 10) {

return a + b + 2; 

} else if (a > 10 && b > 10) { 

return a + b + 4; 

} else return a + b + 3;

} ;




or 




function addWithSurcharge(a, b) {

  let surcharge = 0;

  if (a <= 10) {
    surcharge = surcharge + 1;
  } else {
    surcharge = surcharge + 2;
  }

  if (b <= 10) {
    surcharge = surcharge + 1;
  } else {
    surcharge = surcharge + 2;
  }

  return a + b + surcharge;
}




> in the first example we declare a function addWithSurcharge
>>> it has two parameters
>>> we create if / else if / else statements to execute a block of code
>>> our first condition is to add a + b + 2 if both the values are less than or equal to 10 
>>> our second condition is to add a + b + 4 if both the values are more than 10 
>>> if both the above conditions are not met then we add both the values to 3
>>> a + b + 3 
> in the second example we declare a function addWithSurcharge
>>> in the second example we declare a variable surcharge
>>> we initialize it with a value of 0
>>> we create two if / else statements to execute a block of code within addWithSurcharge
>>> our first condition within the first if / else statement is to add surcharge + 1 
>>>>> if 'a' is less than or equal to 10 and initialize the value to the variable 'surcharge'
>>>>>  or else add surcharge + 2 
>>> our second condition within the second if / else statement is to add surcharge + 1 
>>>>> if 'b' is less than or equal to 10 and initialize the value to the variable 'surcharge'
>>>>>  or else add surcharge + 2
>  in the second example, when we call the function with numbers 
> the function will start executing and updating the surcharge amount 
> it will first check if a is less than or equal to 10
> based on the number it will add original surcharge value 0 + 1 or 2 
> it will then store the value to the variable surcharge
> after it has assessed the parameter a, then it will move to parameter b
> it will perform the same function and will add the surcharge value to the value stored in the variable 'surcharge'; surcharge = surcharge + 1 or 2
> finally when both 'a' and 'b' are analyzed we return the final value of surcharge added to the 'a' and 'b' parameters

No comments:

Post a Comment