Presentation is loading. Please wait.

Presentation is loading. Please wait.

Precedence Operators Error Types

Similar presentations


Presentation on theme: "Precedence Operators Error Types"— Presentation transcript:

1 Precedence Operators Error Types
JavaScript Precedence Operators Error Types

2 Learning Objectives By the end of this lecture, you should be able to:
Identify the ‘operators’ on a given line of code. Identify the precendence (order) in which each of those operations will be carried out. Recognize situations in which you may encounter an ‘NaN’ error code.

3 Where should you put your variables?
It’s okay to have variables anywhere, but remember, you can not use a variable until you declare it. Generally, we try to group all variables we plan on using, together at the beginning of the function.

4 Operator “Precedence”
var result; a = 5; b = 20; result = a + b / 5 - 1; //What is the value of result?! Some key precedence rules: Multiplication and division have higher “precedence” than addition and subtraction. By precedence we mean that, for example, on a given line, a multiplication operation will be done before, say, a subtraction – regardless of which one appears first on the line. Operations that have the same precedence (e.g. addition and subtraction, or multiplicaton and division) are evaluated left to right. Parentheses around operations raise the precendence of those operations. Assignment Operator: Note that the ‘=‘ is an operation! It is called the “assignment’ operator” as we use it to assign a value to a variable. However, this operator has very low precedence. It is almost always the last operation on the line to be executed. Parentheses: You can use parentheses to force the evaluation order: the innermost parentheses are evaluated first. If you have any doubt about how things will be executed when writing a detailed expression, it often helps to use parentheses.

5 Precedence example Answer: var a, b, result; a = 5; b = 20;
Using your knowledge of precedence: Identify the operators on the fourth line Identify the order in which these operations will be executed by the JS interpreter Determine the value of ‘result’ Answer: There are FOUR operators on this line: addition, division, subtraction, and assignment (=). The operator with the highest precendence on this line is division. The operator with lowest precedence is the assignment. So, first we do the division: b/5 = 4. After doing the division, we have two operators with the same precedence: + and -. With operators of the same precedence, we go from left to right. So in this case, we would first do addition, then the subtraction. So we add ‘a’ to 4 to give us 9. After that we do the subtraction to give us 8. The last remaining operator on this line is the assignment operator (‘=‘). This is where we assign the value of 8 to the variable ‘result’.

6 Precedence example var b, result; b = 5; result = b+2 / 2;
What is the value of ‘result’? Even though the ‘b+2’ looks like it should be grouped together – and perhaps this is what the programmer had intended, the first operation that occurs is the division. After that, we do the addition. After that, we assign. So: Operator with the highest precedence is the division: 2/2  gives ‘1’ Operator with next highest precendece is addtition: Add to ‘b’  gives 6 Last remaining operator is the assignment  Assign 6 to ‘answer’ However, if we wanted to first add 2 to b, then we could have put parentheses around it: result = (b+2) / 2. //In this case, ‘answer’ would be assigned 3.5.

7 Precedence practice What about: position = a * 5 + b / 10;
What is the order of operations for the line with the assignment statement below? var a, b, position, result; a = 5; b = 20; result = a + b / ; Answer: b/2  add to a  subtract 1  assign What about: position = a * 5 + b / 10; Answer: a * 5  then b/10  then add the two  assign

8 The assignment operator: ‘ = ‘
The assignment operator has very low precedence. So on a line with several operators, we typically do the assignment last. Therefore, when you see a line with an assignment operation, we typically do the entire right side of line first, and then do the assignment. e.g. a mathematical formula e.g. retreiving the value from a form Examples: celsius = (far-32) * 5.0 / 9; age = document.getElementById('someItem')value; age = parseInt(age);

9 Example: x = x + 1 We can add or subtract from the current value of a variable using the example above. If this line of code seems confusing, recall how the assignment operator works (i.e. right-side first  then assignment). x = 5; x = x + 1; alert(x); What’s the value of ‘x’? Again, recall that because the assignment operator has such “low precedence”, it is the last operation that will take place on that line. Put another way, whenever you have an assignment operator, everything on the right side of the assignment operator (‘=‘) is carried out first. Only then the assignment operation done. So in this case, x will be set to 6.

10 Example of how not understanding precedence can cause problems
To convert a temperature from fahrenheit to celcius you must subtract 32, then multiply by 5 and divide over 9. var celsius, fahrenheit; var fahrenheit = 100; //hard code in a 100 celsius = fahrenheit - 32 * 5.0 / 9; //Can you spot the bug in our code? //JS will first do 32*5.0, and then divide by 9 //It will then subtract the total from Fahrenheit //Thoughts on how we can fix this? celsius = (fahrenheit-32) * 5.0 / 9; // Anything inside parentheses gets carried out // *first*

11 Practice: Create a form that asks the user for a temperature in farheheit. One text box for the temperature One button to submit the form Write a function that outputs the result in celsius. Formula: To convert a temperature from fahrenheit to celcius you must subtract 32 from fahrhenheit, then multiply by 5.0 and divide by 9 Solution on the next slide…

12 File: fahrenheit_celcius_converter.htm
<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <title>Temperature Converter</title> <script type="text/javascript"> function convertToCelcius() { var fahrenheit, celcius; fahrenheit = document.getElementById('txtFahrenheit').value; fahrenheit = parseFloat(fahrenheit ); //people may well enter a decimal here... celcius = (fahrenheit-32)*5.0/9; alert(fahrenheit + " degrees F corresponds to " + celcius + " degrees C."); } </script> </head> <body> <h2>Temperature Converter</h2> <hr> <form id="conversionForm"> Enter a temperature in fahrenheit: <input type="text" id="txtFahrenheit"> <br> <input type="button" value="Convert" onclick="convertToCelcius()" > </form> </body> </html> File: fahrenheit_celcius_converter.htm

13 Other error values you may encounter
NaN Not a number var x = "hello"; x = x * 5; //will generate the ‘NaN’ error // Try it! Infinity Infinity (e.g. 4 / 0) In JavaScript, 4/0 equals “Infinity”. But in mathematics, 4/0 is undefined, which means it has no value.

14 Another Lab Exercise: Let’s write a page that calculates the “Body Mass Index” used in fitness circles as a quick (though now mostly debunked) indicator of a person’s health. It is possible that you have already seen this example in a different lecture. The formula requires the user to enter their height and weight and then calculates their BMI. The formula is: BMI = weight in pounds* 703 divided by height in inches squared.

15 Try to create this page on your own before looking at my solution
The form: The formula for BMI is: Weight*703 / height2 After the user submits the form:

16 START SIMPLE and gradually BUILD
Creating the BMI form START SIMPLE and gradually BUILD Create the form THEN Write the basic outline of your JS function THEN: Test the function by outputting something very simple such as “test” THEN Retreive the values from the form and store them in variables. Output those variables to make sure you have done it correctly. THEN incorporate the formula. THEN and ONLY then: Worry about the visuals. (e.g. colors, graphics, reducing the number of decimals in the BMI, etc) Do NOT move to this step until the JS is working. A user may appreciate the visual components to a page But if the page fails to do what it is supposed to do, then all the visuals in the world won’t matter! Etc

17 Code: File: bmi_calculator.htm
You can learn more about the application of BMI to your health here.


Download ppt "Precedence Operators Error Types"

Similar presentations


Ads by Google