Using arithmetic
operators in JavaScript
Arithmetic Expressions
• Arithmetic evaluation was one of the motivations
for the development of programming languages
• Arithmetic expressions consist of operators,
operands, parentheses, and function calls
Using Arithmetic Operators
Arithmetic operations in JavaScript are
carried out with arithmetic symbols
Same as math class (except multiplication is *
rather than x)
These symbols are called arithmetic
operators
Arithmetic Operators
Multiply 2*4→8
Divide 2 / 4 → 0.5
Modulus 5%2→1
Add 2+4→6
Subtract 2 - 4 → -2
Negate -(5) → -5
JavaScript Arithmetic Operators
Operator Description Example Result
+ Addition x=7 13
y=6
x+y
- Subtraction x=25 2
y=23
x-y
* Multiplication x=15 90
y=6
x*y
/ Division 35/5 7
13/2 6,5
% Modulus (division remainder) 7%2 1
12%9 3
16%4 0
++ Increment x=13 x=14
x++
-- Decrement x=12 x=11
x--
JavaScript Arithmetic Operators
<html>
<body>
<script type="text/JavaScript">
var two = 2;
var ten = 10;
var linebreak = "<br />"
[Link]("two plus ten = ")
var result = two + ten;
[Link](result);
[Link](linebreak);
[Link]("ten * ten = ");
result = ten * ten;
[Link](result);
[Link](linebreak); Output:
[Link]("ten / two = ");
result = ten / two;
[Link](result);
</script>
</body>
</html>
JavaScript Arithmetic Operators
JavaScript Operator Precedence
() Parenthesis
** Exponent
* Multiplication
/ Division
% Modulus (Division
Remainder)
+ Addition
- Subtraction
Order of Precedence for the
Basic Operators
Common Programming Error
It is a syntax error if the operators ==,
!=, >= and <= contain spaces between
their symbols, as in = =, ! =, > = and < =,
respectively.
Order in which a second-degree
polynomial is evaluated
JavaScript Operators
Arithmetic Operators
• Multiplication must be given explicitly with the asterisk ( * )
multiply operator
• Multiply and divide are performed before add and subtract
– Unless grouped by parentheses
• JavaScript does not have an operator for exponents
• Binary operators operate on two operands (like + and *)
• Unary operators operate on one operand (like - for negate)
• Modulus or mod ( % ) divides two integers and returns the
remainder
Operators
• Operator Overload
– Use of an operator with different data types
– Case of interest in JavaScript is +
• Addition
– When used with numbers, it adds
• 4 + 5 produces 9
• Concatenation
– When + is used with strings, it concatenates or
joins the strings together
• "four" + "five" produces "fourfive"
Arithmetic Expressions: Operator
Precedence Rules
• The operator precedence rules for expression
evaluation define the order in which “adjacent”
operators of different precedence levels are
evaluated
• Typical precedence levels
– parentheses
– unary operators
– ** (if the language supports it)
– *, /
– +, -
Using Operators to Build Expressions
JavaScript Operators:
Automatic Type Conversion
• Binary operators +, -, *, /, % convert both
operands to Number
– Exception: If one of operands of + is String then
the other is converted to String
• Relational operators <, >, <=, >= convert both
operands to Number
– Exception: If both operands are String, no
conversion is performed and lexicographic string
comparison is performed
JavaScript Numbers
• Syntactic representations of Number
– Integer (42) and decimal (42.0)
– Scientific notation (-12.4e12)
– Hexadecimal (0xfa0)
• Internal representation
– Approximately 16 digits of precision
– Approximate range of magnitudes
• Smallest: 10-323
• Largest: 10308 (Infinity if literal is larger)
Elements of JavaScript Statements
b=2; Identifiers
sum = sum + 49 ; Operators
name = “Bhola” + “ Continental” ; Literals
x = [Link] ( x ) ; Punctuation
JavaScript Operators
• Operators operate on operands to achieve the
desired results
• JavaScript has numerous operators, classified
in many categories.
–Assignment operators -- Arithmetic
operators
–Comparison operators -- String operators
–Logical operators
Example
var x = 17; Ans = x + y;
Ans => 29
var y = 12;
Ans = z + x;
var z = “dog”; Ans =>dog17
var q = “17”; Ans = x + q;
Ans => 1717
Arithmetic Operators
• Perform mathematical calculations
– Addition, subtraction, multiplication, division
– Returns the modulus of a calculation
• Arithmetic binary operators
Arithmetic Operators
Operator Description Example Result
+ Addition x=y+2 x=7
- Subtraction x=y-2 x=3
* Multiplication x=y*2 x=10
/ Division x=y/2 x=2.5
% Modulus (division x=y%2 x=1
remainder)
++ Increment x=++y x=6
-- Decrement x=--y x=4
Given that y=5.
Arithmetic Operators
Common Programming Error
Confusing the + operator used for string concatenation
with the + operator used for addition often leads to
undesired results. For example, if integer variable y has
the value 5, the expression "y + 2 = " + y + 2 results in "y
+ 2 = 52", not "y + 2 = 7", because first the value of y
(i.e., 5) is concatenated with the string
"y + 2 = ", then the value 2 is concatenated with the
new, larger string "y + 2 = 5". The expression
"y + 2 = " + (y + 2) produces the string
"y + 2 = 7" because the parentheses ensure that
y + 2 is executed mathematically before it is converted
to a string.
Arithmetic Operators
var divisionResult = 15 / 6;
var modulusResult = 15 % 6;
[Link]("<p>15 divided by 6 is "↵
+ divisionResult + ".</p>"); // prints '2.5'
[Link]("<p>The whole number 6 goes into 15
twice,↵
with a remainder of "+ modulusResult + ".</p>");↵ //
prints '3'
Arithmetic Operators
• Arithmetic unary operators
– Performed on a single variable using unary operators
– Increment (++) unary operator: used as prefix
operators
• Prefix operator placed before a variable
– Decrement (--) unary operator: used as postfix
operator
• Postfix operator placed after a variable
– Example: ++count; and count++;
• Both increase the count variable by one, but return different
values
Arithmetic Operators
Arithmetic Operators
Example
• += compound addition assignment operator
– Used to combine two strings and to add numbers
Example
Increment operator
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <script>
• var a = 22;
• a++;
• var b = a;
• [Link]("demo").innerHTML = b;
• </script>
• </body>
• </html>
23
Decrement operator
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <script>
• var a = 22;
• a--;
• var b = a;
• [Link]("demo").innerHTML = b;
• </script>
• </body>
• </html>
21
Exponentiation operator
• <!DOCTYPE html>
• <html>
• <body>
• <p id="demo"></p>
• <script>
• var a = 4;
• [Link]("demo").innerHTML = a ** 3;
• </script>
• </body>
• </html>
64
White Spaces & Line Breaks
• White spaces: The space & the tab characters
• JavaScript ignores any extra white spaces or line
breaks that you put in the code
• This gives you the freedom of using them for
making your code appear neat and readable
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
while ( x > 0) {remaind = x % 2; y = remaind + y;}
while ( x > 0) {
remaind = x % 2;
y = remaind + y;
}
30
Example
• <html>
• <body>
• <script type="text/javascript">
• <!--
• var x = 50;
• var y = 20;
• var z = “Hello";
• var linebreak = "<br />";
• [Link](“x + y = ");
• result = x + y;
• [Link](result);
• [Link](linebreak);
• [Link](“x - y = ");
• result = x - y;
• [Link](result);
• [Link](linebreak);
Example (continue)
• [Link](“x / y = ");
• result = x / y;
• [Link](result);
• [Link](linebreak);
• [Link](“x % y = ");
• result = x % y;
• [Link](result);
• [Link](linebreak);
• [Link](“x + y + z = ");
• result = x + y + z;
• [Link](result);
• [Link](linebreak);
• //-->
• </script>
• </body>
• </html>
Example (continue)
Result:
x + y = 70
x - y = 30
x / y = 2.5
x % y = 10
x + y + z = 70Hello
Example
<script type="text/javascript"> <!--
var a = 33; var b= 10; var c = "Test";
var linebreak = "<br />";
[Link]("a + b = ");
result = a + b;
[Link](result);
[Link](linebreak);
[Link]("a - b = ");
result = a - b;
[Link](result);
[Link](linebreak);
[Link]("a / b = ");
result = a / b;
[Link](result);
[Link](linebreak);
[Link]("a % b = ");
result = a % b;
[Link](result);
[Link](linebreak);
Example (continue)
[Link]("a + b + c = ");
result = a + b + c;
[Link](result);
[Link](linebreak);
a = a++;
[Link]("a++ = ");
result = a++;
[Link](result); [Link](linebreak);
b = b--;
[Link]("b-- = ");
result = b--;
[Link](result); [Link](linebreak);
//-->
</script>
Output:
a + b = 43
a - b = 23
a / b = 3.3
a%b=3
a + b + c = 43Test
a++ = 33
b-- = 10
Example (area of rectangle)
• <script>
• var length = 20 ;
• var width = 10 ;
• var area = length * width;
• [Link](" Area of rectangle is ", area);
• </script>
Area of rectangle is 200
Expressions can combine
arithmetic operators
Expressions can have more than one
operator:
var length = 5;
var width = 6;
var perimeter;
perimeter = length*2 + width * 2;
Perimeter now has a value of 22
The Espresso Program
The Espresso Program
• Line 3 is a basic conditional statement
• Lines 4-4c use an if statement with
conditionals in the then statement
• Line 5 uses basic if statement
• Lines 6, 7 compute using arithmetic
operators
JavaScript Functions
• The keyword function is used to define
a function (subroutine):
function add(x,y) {
return(x+y);
}
• No type is specified for arguments!
What is the value of:
add(5,9) 14
add(“5”,”9”) 14
add(“Hello”,”Murat”) “HelloMurat”
add(6,”Hello”) “6Hello”
“7.24bim6.28”
add(“7.24bim”,6.28)
Functions
• Function definition
– Lines making up a function
• Named function syntax
function name_of_function(parameters) {
statements;
}
• Anonymous function syntax
function (parameters) {
statements;
}
Example
if ( x != 0 )
result = y / x;
else
result = “not defined”;
Functions
• Parameter
–Variable used within a function
–Placed within parentheses following a
function name
–Multiple parameters allowed
calculateVolume(length, width, height)
Functions
• Function statements
– Do the actual work
– Contained within function braces
• Put functions in an external .js file
– Reference at bottom of body section
function calculateVolume(length, width,
height) {
var volume = length * width * height;
[Link](volume);
}
Functions
var stateTax;
[Link](stateTax);
stateTax = 40;
[Link](stateTax);
stateTax = null;
[Link](stateTax);