In this article, we will see how to subtract two numbers in JavaScript. A Basic arithmetic operation known as Subtraction involves taking one number (the “subtrahend”) away from another (the “minuend”) in order to calculate their difference. It is denoted by the minus sign (-). A subtraction’s outcome is referred to as the “difference.”
Syntax:
Result = Minuend - Subtrahend
Let’s take two numbers:
Input: a = 10 , b = 20
Output:
b - a = 20 - 10 = 10
a - b = 10 - 20 = -10
Table of Content
Using the Negative Operator ( – ) in Console
We can directly perform Subtraction operations in the console by using the “console.log()” statement by providing two operands that will print the exact difference value.
Example: This example describes the subtraction of two numbers using “console.log”.
let a = 10; let b = 20; // Subtract directlty console.log(a - b); // -10
console.log(b - a); // 10
// Subtract by using another variable let c = b - a; console.log(c); // 10
// Subtract without any variable console.log(10 - 20); //-10
console.log(20 - 10); //10
console.log(20 - 10 - 10); //0
|
-10 10 10 -10 10 0
Using User Defined Functions
Functions in Javascript can be used to calculate the difference between the 2 operands. The function will take parameters as 2 numbers, then the function will return the subtraction of the input parameters.
Syntax:
function fun_name (param1 , param2) {
return param1 - param2 ;
}
Example: This example describes the subtraction of 2 numbers using a Function.
// First variable let a = 10; // Second variable let b = 20; // Funciton to subtract two variables function subtract(a, b) {
return a - b;
} // For printing the result console.log( "after subtraction : " + subtract(a, b));
|
after subtraction : -10
Using Arrow Function
The subtraction of two numbers can also be done using the arrow function, where the 2 variables are passed as a parameter of that function and return the value after subtraction
Syntax:
let var_name = (param) => {
// code
}
Example: This example describes the subtraction of 2 numbers using the Arrow function.
// First variable let a = 10; // Second variable let b = 20; // Arrow funciton for subtraction of two numbers let ans = (a, b) => a - b; // For printing the result in console console.log( "after subtraction : " + ans(a, b));
|
after subtraction : -10
Using the Subtract Assignment Operator
It subtracts the right operand from the left operand and assigns the result to the left operand. The value provided on the right-hand side will decide how much value it must be decreased.
Syntax:
var_name -= value;
Example: This example describes the subtraction of 2 numbers using the subtraction AND assignment operator.
// Create a variable let a = 20; let b = 10; a -= b; // Print the result console.log(a); // 10
|
10