1
    function show() {
        let date_ = new Date();
    
        let sec = String(date_.getSeconds());
        fill_gaps(sec);
    
        function fill_gaps(candidate) {
            if (candidate.length < 2) {
            candidate = "0" + candidate;
          } else {
          candidate = candidate;
         }
       }
    
        time_ = String(`${sec}`);
        console.log(time_)
      }

The fill_gaps() function is supposed to change the var sec value; but it isn't changing the value outside the function. My guess is that it is not changing on global scope.

I know this is a basic problem but I can't figure it out as I am still a beginer.

Expected:

console.log(time_) = 0("and the current second")

Actual:

console.log(tiem_) = ("the current second")
Moritz Ringler
  • 9,772
  • 9
  • 21
  • 34
luci
  • 38
  • 4
  • 1
    strings are passed as a value inside the function in JS not as a reference. – mgm793 Feb 23 '23 at 13:58
  • 1
    Does this answer your question? [Is JavaScript a pass-by-reference or pass-by-value language?](https://stackoverflow.com/questions/518000/is-javascript-a-pass-by-reference-or-pass-by-value-language) – mgm793 Feb 23 '23 at 13:59
  • are you declaring a function inside another function? – Chris G Feb 23 '23 at 14:00
  • Chris G - am i doing something wrong? – luci Feb 23 '23 at 14:26

1 Answers1

2

Edit: You were missing a return statement in your fill_gaps function, you were calling it but you weren't doing anything with it

function show() {
  let date_ = new Date();

  let sec = String(date_.getSeconds());
  sec = fill_gaps(sec); //call your function like this, save its value inside the sec variable

  time_ = String(`${sec}`);
  console.log(time_)
}

//this outside, it is a separate function
function fill_gaps(candidate) {
  if (candidate.length < 2) {
    candidate = "0" + candidate;
  } else {
    candidate = candidate;
  }
  return candidate;//you were missing a return statement
}

show();
Chris G
  • 1,598
  • 1
  • 6
  • 18