Sunday, November 18, 2018

JavaScript Arithmetic

JavaScript Arithmetic Operators

Arithmetic operators perform arithmetic on numbers (literals or variables).


Operator                                         Description
+                                                    Addition
-                                                     Subtraction
*                                                     Multiplication
/                                                      Division
%                                                   Modulus (Remainder)
++                                                  Increment
--                                                    Decrement


Arithmetic Operations

A typical arithmetic operation operates on two numbers.
The two numbers can be literals:

Example:


var x = 100 + 50;


var x = a + b;

var x = (100 + 50) * a;


Operators and Operands

The numbers (in an arithmetic operation) are called operands.
The operation (to be performed between the two operands) is defined by an operator.
OperandOperatorOperand
100+50

Adding

The addition operator (+) adds numbers:


var x = 5;
var y = 2;
var z = x + y;

Subtracting

The subtraction operator (-) subtracts numbers.

var x = 5;
var y = 2;
var z = x - y;

Multiplying

The multiplication operator (*) multiplies numbers.

var x = 5;
var y = 2;
var z = x * y;

Dividing

The division operator (/) divides numbers.

var x = 5;
var y = 2;
var z = x / y;

Remainder

The modulus operator (%) returns the division remainder.

var x = 5;
var y = 2;
var z = x % y;

In arithmetic, the division of two integers produces a quotient and a remainder.
In mathematics, the result of a modulo operation is the remainder of an arithmetic division.

Incrementing

The increment operator (++) increments numbers.

var x = 5;
x++;
var z = x;

Decrementing

The decrement operator (--) decrements numbers.

var x = 5;
x--;
var z = x;

Operator Precedence

Operator precedence describes the order in which operations are performed in an arithmetic expression.

var x = 100 + 50 * 3;

Is the result of example above the same as 150 * 3, or is it the same as 100 + 150?
Is the addition or the multiplication done first?
As in traditional school mathematics, the multiplication is done first.
Multiplication (*) and division (/) have higher precedence than addition (+) and subtraction (-).
And (as in school mathematics) the precedence can be changed by using parentheses:

var x = (100 + 50) * 3;


Share:

0 comments:

Post a Comment

Contact Form

Name

Email *

Message *

Popular Posts

Blog Archive

Blog Archive

Hassan.mosmer1@gmail.com