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

114
Views
Property of object not returning the expected value in Javascript

I am new to javascript and was trying to create a stopwatch object as described in a youtube video. Following is the code:

function Stopwatch(){
    let durationVal = 0;
    let startFlag = 0;

    this.start = function(){
            if (startFlag === 0){
                    durationVal = Date.now()
                    startFlag = 1;        
            }
            else{
                    throw new Error('Stopwatch is already running')
            }
    }

    this.stop = function(){
            if(startFlag === 1){
                    durationVal = Date.now() - durationVal
                    startFlag = 0;
            }
            else{
                    throw new Error('Stopwatch is not running')
            }
    }

    this.duration = durationVal;

    this.reset = function(){
            durationVal = 0;
    }

}

When I try to create an object and access its duration property

let sw = new Stopwatch()
sw.start()
sw.stop()
console.log(sw.duration)

It returns a zero. However, when I change my javascript to use a method to get the duration value:

 this.duration = function(){
            return durationVal;
 }

it gives the correct value. Can you explain why?

about 4 years ago · Juan Pablo Isaza
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!