Ali Shahsavar
Ali Shahsavar

Reputation: 33

Difficulty understanding a piece of javascript code

This piece of simple javascript code is a timer. that I want to put 0 before the second. I put the if after the else, but the code didn't work, but when I put the code in the commented part, it worked, tell me why this happened?

let minute = +prompt("Enter For Min :");
let second = +prompt("Enter For Sec :");

let timer = setInterval(function () {
  if (minute == 0 && second == 0) {
    document.body.innerHTML = `Time Out!`;
    clearInterval(timer);
  } else {
    if (second < 10 && second.toString().indexOf(0) !== 0) {
      second = "0" + second;
    }//This code should paste to line 17 to work but why?
    --second;
    if (second == -1) {
      minute -= 1;
      second = 59;
    }
    //This Place
    document.body.innerHTML = `Timer ${minute} : ${second}`;
  }
}, 1000);

Upvotes: 0

Views: 31

Answers (1)

David
David

Reputation: 218798

Because numbers are numbers and strings are strings. When you do this, you're turning second into a string:

second = "0" + second;

If you immediately display that string, it will include the pre-pended 0 character. However, when you do this it becomes a number again:

--second;

So if you display the value it won't have any leading zero digits.

Overall, the structure of your code should be:

  1. Gather input
  2. Perform calculation
  3. Display output

This part is calculation:

--second;
if (second == -1) {
  minute -= 1;
  second = 59;
}

This part is displaying output:

if (second < 10 && second.toString().indexOf(0) !== 0) {
  second = "0" + second;
}
document.body.innerHTML = `Timer ${minute} : ${second}`;

Keep them logically grouped as such. Formatting the data for display (such as prepending characters to a numberic value) is part of displaying the output.

Upvotes: 1

Related Questions