How To Build A Simple Calculator in JavaScript

Before we proceed with this article, I want to make sure you have strong knowledge on :
what objects are and how you can create one
what methods are and how you can invoke one

We will use a constructor function to build this calculator but with the methods below:

  • sum: for adding numbers
  • subtract: for subtracting numbers
  • multiply: for multiplying numbers
  • divide: for dividing numbers

LET US BEGIN

I will name our constructor function calculator and I will provide just 2 parameters that will be used for operation.

function calculator(a, b){

}

Now we have to create our first method. This method will be the sum method and all it will do is return the sum of the two numbers

function calculator(){
this.sum = function(a, b){
return(a+b);
}
}

We can quickly test this method by creating a new instance of the function and then, we invoke the sum method, providing 2 arguments which are the numbers, to sum up.

const calculate = new calculator();
console.log( calculate.sum(10, 20) );

 

You can see that the calculator returned the exact value that we expected which is the sum of 10 and 20.

We can go ahead and create other methods.

function calculator(){
this.sum = function(a, b){
return(a+b);
};
this.multiply = function(a, b){
return(a*b);
};
this.divide = function(a, b){
return(a/b);
};
this.subtract = function(a, b){
return(a-b);
};
}

Now let us test our calculator. I will use 20 and 10 as a and b.

const a = 20;
const b = 10;
const calculate = new calculator();
console.log( "Sum "+calculate.sum(a, b) );
console.log( "Subtract "+calculate.subtract(a, b) );
console.log( "Multiply "+calculate.multiply(a, b) );
console.log( "Divide "+calculate.divide(a, b) );

Here's the result

 

The result is exactly what we expected!

What other methods do you think you can add to make this an advanced calculator? 

Go on and play with it!

Thank you for reading.


Simon Ugorji

16 Blog posts

Comments