-4

I want the check function to prepend "0" to hour if it is below 10.

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hour = date.getHours();
var minutes = date.getMinutes();

function check(x) {
  if (x < 10) {
    x = '0' + x;
  }
};
check(hour);
console.log(hour);

But when I check console.log(hour); it still returns the previous value. Why is this the case?

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
OskiBoski
  • 15
  • 3
  • `return "0" + x;` and `return x;` outside the `if`; then `hour = check(hour)`. Assignment is useless. You could also simply use `var hour = String(date.getHours()).padStart(2, "0");`. – Sebastian Simon Nov 17 '19 at 08:38
  • Use ```hour = '0' + x``` instead of ```x = '0' + x``` .. – Maniraj Murugan Nov 17 '19 at 08:41
  • The `x` you assign inside the function is another variable which is not related to the global variable `x` in any way. – Maheer Ali Nov 17 '19 at 08:42
  • I think to understand it you must investigate the concepts of passing a parameter "by value" or "by reference". It happens because, when you are passing `hour` as parameter, you are actually only passing a copy of the value `hour` has, not its memory address itself (that would be passing "by reference"). That is why despite you change `hour`value inside the function, it doesn´t affect outside the function, because inside the function you were only using `hour` value but not making a real assignment to its memory address. https://www.javascripttutorial.net/javascript-pass-by-value/ –  Jul 22 '21 at 17:31

1 Answers1

0

You need to return the value and you need to take the value from the function for an output or assignment.

function check(x) {
    if (x < 10) {
        return '0' + x;
    }
    return x;
}

In this case, I would change the name of the function to getFormatted and uzse a more abstract approach.

function getFormatted(value, size = 2) {
    return value.toString().padStart(size, 0);
}

var date = new Date();
var day = date.getDate();
var month = date.getMonth() + 1;
var year = date.getFullYear();
var hour = date.getHours();
var minutes = date.getMinutes();

console.log(getFormatted(hour));
Nina Scholz
  • 376,160
  • 25
  • 347
  • 392
  • I figured it out in another way. As I can see there is no way to add hour new value inside a function. So i did it like that: ``` hour = check(hour); ``` and it works! :) THANKS everyone for your effort THANKS – OskiBoski Nov 17 '19 at 08:53