Operators and Operator Precedence In JavaScript
In JavaScript, precedence determines the order in which operators are evaluated in an expression. Understanding operator precedence is crucial for writing correct and predictable JavaScript code. It is recommended to use parentheses when necessary to clarify the intended order of operation. Operators with higher precedence are evaluated first. Here are some examples of operator precedence in JavaScript:
Table Of Contents
Arithmetic Operators
Multiplication, division, and modulo operators have higher precedence than addition and subtraction.
console.log(3+4*5);
Output:
23
As multiplication is performed first.
Comparison Operators
Comparison operators such as <
, >
, <=
, and >=
have higher precedence than equality operators like ==
and ===
.
console.log(2 + 3 < 4 * 5);
Output:
True
Evaluates to true
because the comparison is evaluated before addition.
Logical Operators
Logical NOT (!
) has the highest precedence, followed by logical AND (&&
), and logical OR (||
) has the lowest precedence.
console.log(!true && false || true);
Output:
True
Evaluates to true
because the NOT operator is evaluated first, followed by the AND and OR operators.
Assignment Operators
Assignment operators, such as =
, +=
, -=
have a lower precedence compared to arithmetic and logical operators.
var x = 2 + 3 console.log(x);
Output:
5
assigns the value 5 to the variable x
after performing the addition operation.
Grouping with Parentheses
Parentheses can be used to enforce a specific order of evaluation, overriding the default precedence rules.
var x = (2 + 3) * 4 console.log(x);
Output:
20
evaluates to 20 because the addition inside the parentheses is performed first.
Read Also:
- How to print hello world using javascript
- How to redirect to another page using javascript
- How to refresh page on specific time using javascript
- How to remove a property of JavaScript object
- How to remove a specific item from an array in javascript
- How to scroll to the top of the page using javascript
- How to set default argument values in JavaScript functions
- How to validate an email address Using JavaScript
- What is the reverse of the push function in javascript
- Write a JavaScript function to check if an input is an array
Comments
Post a Comment