Hacker News new | ask | show | jobs
by morecoffee 3240 days ago
The numerous overloads of 'this' is one of the things that turned me off from JS. It's great that bloggers explain the usages and how it works in different scenarios, but really the better solution would be to not have the problem at all. I would trade overloading for verbosity. An editor can easily squash the latter, where as a human has to train for the former.
2 comments

But there is no "overload" to `this` in JavaScript. It works the same way every time. It's an implicit parameter that is passed when you call the function. It can also be bound, just like all the explicit parameters. The six ways the author presents are just an incomplete list of "Ways you can create an execution context in JavaScript".

This may be confusing to people who expect `this` to have a certain functionality when coming from a different language, but `this` is very consistent in JavaScript. It's just not the kind of consistency people seem to expect.

There's a great way to avoid having the problem - don't use the implicit parameter! What exactly is it giving you, anyway? In almost all cases where people fail to use `this`, they essentially create a function to pass it explicitly. Why not just do that from the get go?

It may work the same way every time, but the way it works the same is different depending on context.
We can save time by listing the worthwhile features of JavaScript.

The OR operator (||) is nice syntactic sugar for returning the first non-null value. Just like SQL's COALESCE.

  let a = null
  let b = 123
  let result = a || b
result now equals 123.

Dang it. Now I can't remember the other thing I like about JavaScript.

Oh, I do like using the shebang preamble for running nodejs scripts from the bash command line.

    let a = 0
    let b = 123
    let result = a || b
sets result to 123, but 0 !== null.
EDIT: Rereading parent comment I realize you already know all the below, but maybe parent doesn't quite?? Original comment: That's kind of fundamental expectation within JavaScript, though: 0 is a falsy value. The || doesn't check for null, it coerces the first expression to a boolean, and if it is true, returns the first expression. If it is false, then it returns the second expression (if I recall correctly!). If 0 being falsy is a problem, then the || might not be the easiest/clearest way to do what you need. Since you'd end up needing to nest some separate check for zero on the first expression. In which case you could just handle all your logic in that check.