+ 3

how does this first function works?

function addZero(x) { if (x < 10) { return "0" + String(x); } else { return String(x); } } function printTime() { var d = new Date(); var hours = addZero(d.getHours()); var mins = addZero(d.getMinutes()); var secs = addZero(d.getSeconds()); document.body.innerHTML = hours + ":" + mins + ":" + secs; } setInterval(printTime, 1000); Why do I need to put String()? If I remove it works the same way.

20th Mar 2019, 2:26 AM
Gabriel Junior
Gabriel Junior - avatar
1 Odpowiedź
+ 6
String() function is converting int value into string, which is required in some languages, in some language like python, you cannot directly join a string and an int value, you have to convert that int into string by str() function. But in JavaScript, it is not required. You can directly concate a string and an int here. So feel free to remove that.
20th Mar 2019, 6:15 AM
Letsintegreat
Letsintegreat - avatar