Arithmetic Operators Precedence and Associativity in TypeScript
Precedence
Associativity
If we talk about the precedence of the multiplication and division operators then you will find, these operators contain the same precedence. Now let's see an example.(b) 50/5*2 = 5.
Then, what is the correct result?
The given table tells you which operator has higher precedence and how to associativity on them. In this table, precedence is given in decreasing order in other words precedence category one (1) has the highest priority.
| Precedence | Category | Symbol | Name | Associativity |
| 1 | Primary | (<Numeric_expression>) |
Parenthesis |
Right-Left |
| 2 | Unary | + |
Unary plus |
Right-Left |
| 3 | * |
Multiplication |
Left-Right |
|
| 4 | Binary | + |
Addition |
Left-Right |
After Step 1 your project has been created. Solution Explorer, which is at the right side of Visual Studio, contains the js file, ts file, CSS file, and Html files.
Step 3
The code for the Arithmetic Operators Precedence and Associativity program:
The code for the Arithmetic Operators Precedence and Associativity program:
ArithmeticPrecedenceNAssociativity.ts
- class ArithmeticPrecedenceNAssociativity {
- Myfunction() {
- var PreRes: number = 100 + 5 * 10;
- document.write("Precedence res=" + PreRes + "<br/>");
- var AssoRes: number = 100 / 5 * 2;
- document.write("Associativity res=" + AssoRes);
- }
- }
- window.onload = () => {
- var call = new ArithmeticPrecedenceNAssociativity();
- call.Myfunction();
- }
Note: In the above-declared program, multiplication operation is performed first, because the multiplication operator has greater precedence than the addition operator. And in the associativity part, two operators (such as (/) and (*)) with the same precedence as the same operand, left-to-right associativity will cause the left-most operator to be applied first, in other words, the divide operation is performed first and then the multiplication operation is performed.
default.html
- < !DOCTYPEhtml >
- <
- htmllang = "en"
- xmlns = "http://www.w3.org/1999/xhtml" >
- <
- head >
- <
- metacharset = "utf-8" / >
- <
- title > TypeScript HTML App < /title>
- <
- linkrel = "stylesheet"
- href = "app.css"
- type = "text/css" / >
- <
- scriptsrc = "app.js" > < /script>
- <
- /head>
- <
- body >
- <
- divid = "content" / >
- <
- /body>
- <
- /html>
app.js
- var ArithmeticPrecedenceNAssociativity = (function() {
- function ArithmeticPrecedenceNAssociativity() {}
- ArithmeticPrecedenceNAssociativity.prototype.Myfunction = function() {
- var PreRes = 100 + 5 * 10;
- document.write("Precedence res=" + PreRes + "<br/>");
- var AssoRes = 100 / 5 * 2;
- document.write("Associativity res=" + AssoRes);
- };
- return ArithmeticPrecedenceNAssociativity;
- })();
- window.onload = function() {
- var call = new ArithmeticPrecedenceNAssociativity();
- call.Myfunction();
- };
Step 4
Output


Join the conversation! Your thoughts help the community grow.