Professional Documents
Culture Documents
JavaScript operators are classified into six categories based on the type of action
they perform on operands.
Operator Description
+ Addition
- Subtraction
* Multiplication
/ Division
% Modulus (Remainder)
++ Increment
-- Decrement
For Example:
var x = 100 + 50;
Var y=22-23+1*25;
<!DOCTYPE html>
<html>
<body>
<p>A typical arithmetic operation takes two numbers (or expressions) and
produces a new number.</p>
<p id="demo"></p>
<script>
var a = 3;
var x = (100 + 50) * a;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body>
<p>Input your age and click the button:</p>
<input id="age" value="18" />
<button onclick="myFunction()">Try it</button>
<p id="demo"></p>
<script>
function myFunction() {
var age, voteable;
age = document.getElementById("age").value;
voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}
</script>
</body>
</html>
Logical operators are used to determine the logic between variables or values.
Syntax: variablename = (condition) ? value1:value2
Given that x = 6 and y = 3, the table below explains the logical operators:
Operator Description Example
|| or (x == 5 || y == 5) is false
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Comparison</h2>
<p>The AND operator (&&) returns true if both expressions are true, otherwise it returns false.</p>
<p id="demo"></p>
<script>
var x = 6;
var y = 3;
document.getElementById("demo").innerHTML =
(x < 10 && y > 1) + "<br>" +
(x < 10 && y < 1);
</script>
</body>
</html>
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
^= x ^= y x=x^y
|= x |= y x=x|y
**= x **= y x = x ** y
<!DOCTYPE html>
<html>
<body>
<h2>The *= Operator</h2>
<p id="demo"></p>
<script>
var x = 10;
x *= 5;
document.getElementById("demo").innerHTML = x;
</script>
</body>
</html>
If
if-else
if-else if
switch
Syntax:
if (condition)
{
// one or more statements;
}
Presented by Muhammad Ehtisham Siddiqui (BSCS)
Example of IF Statements
19
The if-else if statements allow you to check multiple conditions and specify
a different block to be executed for each condition.
The flow of these statements begins with the if statement followed by
multiple else if statements and finally by an optional else block.
The entry point of execution in these statements begins with the if
statement.
If the condition in the if statement is false, the condition in the immediate
else if statement is evaluated.
Syntax:
if (condition)
{ // one or more statements; }
else if (condition)
{ // one or more statements; }
else { // one or more statements; }