3 ms·
About #2 Wasn't so sure about typescript so I tested it to confirm that it worked. But in Python3, the default arguments are evaluated at module time loading if
by bengalister 6y ago
About #2
Wasn't so sure about typescript so I tested it to confirm that it worked.
But in Python3, the default arguments are evaluated at module time loading if I am not mistaken. The following will display roughly the same timestamp
from datetime import datetime
import time
print(datetime.utcnow())
def show_ts(d=datetime.utcnow()):
print(d)
time.sleep(5)
show_ts()
where as in TS, the 2nd one will be roughly 5s older:
const now = Date.now();
console.log(now);
function logTs(d=Date.now()) {
console.log(d);
}
setTimeout(()=> {
logTs();
}, 5000);
- horsawlarway 6y agoThat's because default params in JS are essentially syntactic sugar ex - function example(a = 1) { ... } behaves the same as function example(a) { a = (typeof a !== 'undefined') ? a : 1 ... }
- sorahn 6y agoWhich also means the suggestion to use ?? has a different result then using a default param. ?? will catch both null and undefined, where as a default parameter will only trigger on undefined.
- horsawlarway 6y agoYup, you're absolutely correct. Null is considered a valid value for a default param. function test(a = 1) { console.log(a) } test() // -> 1 is printed test(null) // -> null is printed test(undefined) // -> 1 is printed
- nawgz 6y ago?? catches any falsy value, so it is quite semantically different than default arguments, and also quite different from ||
- Dylan16807 6y agoDid you write that backwards? || checks for falsy, ?? checks for null/undefined
- Dylan16807 6y agoNot because. You could have sugar evaluated once, sugar evaluated each time, not-sugar evaluated once, or not-sugar evaluated each time.
- tempodox 6y agoEvents that happen at a later time are called “younger”, not “older”. If you were born at a later date than me, you're younger than me.
- bengalister 6y agoYes, the logging event is younger, the timestamp displayed is of greater value. Considering the epoch time as the date of birth the displayed timestamp is older. Probably a translation issue from my native language.