Addition, subtraction, multiplication, and division are basic Arithmetic operations in JavaScript.
Addition Code: The addition operator (+
) adds numbers:
var x = 5;
var y = 5;
var z = x + y;
Subtraction code: The subtraction operator (-
) subtracts numbers.
var x = 10;
var y = 5;
var z = x - y;
Multiplication Code: The multiplication operator (*
) multiplies numbers.
var x = 5;
var y = 2;
var z = x * y;
Division Code: The division operator (/
) divides numbers.
var x = 10;
var y = 2;
var z = x / y;
JavaScript addition, subtraction, multiplication, division Examples
HTML complete example code for all basic athematic operations in JS (JavaScript). Users can choose or enter and select the option to calculate value dynamically.
In the example we used bootstrap and jQuery.
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script>
<link href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" rel="stylesheet">
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>Addtion, Substraction, Divide & Multiplication using javaScript!</title>
<script>
function Calc(){
var val1 = document.getElementById("val1").value;
var val2 = document.getElementById("val2").value;
var opt = document.getElementById("opt").value;
var ans = eval(val1 + opt + val2);
document.getElementById("ans").value = ans;
}
</script>
</head>
<body>
<div class="container">
<div class="row">
<h3>Addition, Subtraction, Multiplication & Division using JavaScript!</h3>
<hr />
<div class="col-lg-1">
<label for="desc">Value 1:</label>
</div>
<div class="col-lg-1">
<input type="number" class="form-control" id="val1" value="5" required>
</div>
</div>
<br />
<div class="row">
<div class="col-lg-1">
<label for="desc">Value 2:</label>
</div>
<div class="col-lg-1">
<input type="number" class="form-control" id="val2" value="2" required>
</div>
<div class="col-lg-1">
<select id="opt" class="form-control">
<option>+</option>
<option>-</option>
<option>*</option>
<option>/</option>
</select>
</div>
</div>
<br />
<div class="row">
<div class="col-lg-1">
<label for="desc">Answer:</label>
</div>
<div class="col-lg-1">
<input type="text" class="form-control" id="ans" readonly>
</div>
<div class="col-lg-1">
<button type="submit" name="submit" class="btn btn-success" onClick="Calc()">Submit</button>
</div>
</div>
</div>
</body>
</html>
Output:
The simple table shows the Arithmetic Operators
Arithmetic Operators | Operation | Example |
---|---|---|
+ | Addition | 10 + 2 = 12 |
– | Subtraction | 10 – 2 = 8 |
* | Multiplication | 10 * 2 = 20 |
/ | Division | 10 / 2 = 5 |
% | Modulus – It returns the remainder after the division | 10 % 2 = 0 (Here remainder is zero). If it is 10 % 3 then it will be 1. |
Do comment if you have any doubts on this JavaScript topic.
Note: The All JS Examples codes are tested on the Firefox browser and the Chrome browser.
OS: Windows 10
Code: HTML 5 Version