Hacker News new | past | comments | ask | show | jobs | submit login

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);



That'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
  ...
  }


Which 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.


?? catches any falsy value, so it is quite semantically different than default arguments, and also quite different from ||


Did you write that backwards? || checks for falsy, ?? checks for null/undefined


Yup, 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


Not because.

You could have sugar evaluated once, sugar evaluated each time, not-sugar evaluated once, or not-sugar evaluated each time.


Events 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.


Yes, 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.




Guidelines | FAQ | Lists | API | Security | Legal | Apply to YC | Contact

Search: