Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

89
Views
Javascript Closures Exercise

Got this exercise from school:

Implement the calculate function that returns an object that gives the ability to perform the four mathematical operations (sum, subtraction, multiplication, and division) on the same number and finally prints the result.

TIP: To concatenate the methods just return the reference to the object itself ($this)

Example:

calculator .add(2) // 2 .add(4) // 6 .multiply(3) // 18 .sub(1) // 17 .sub(3) // 14 .divide(2) // 7 .printResult();

What I did:

function calculate() {

  let result = 0;
  
  let calculator = {
    add: function(number) {
      return result += number;
    },
    multiply: function(number) {
      return result *= number;
    },
    sub: function(number) {
      return result -= number;
    },
    divide: function(number) {
      return result /= number;
    },
    printResult: function() {
      return result;
    }
  }

  return calculator;
  
}

const calculator = calculate();
calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); // The result will be: 7

Please help me I know it's wrong but I did not understand closures with objects. Also give me explanations.

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

The calculator methods add, multiply...etc should return the calculator object (which is this), not the result. So with a minor modification, it will work

function calculate() {
  let result = 0;
  
  let calculator = {
    add: function(number) {
      result += number;
      return this;
    },
    multiply: function(number) {
      result *= number;
      return this;
    },
    sub: function(number) {
      result -= number;
      return this;
    },
    divide: function(number) {
      result /= number;
      return this;
    },
    printResult: function() {
      return result;
    }
  }
  return calculator;
}

const calculator = calculate();
let result = calculator.add(2).add(4).multiply(3).sub(1).sub(3).divide(2).printResult(); 
// The result will be: 7
console.log(result);

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!