←back to thread

498 points azhenley | 1 comments | | HN request time: 0.236s | source
Show context
stevage ◴[] No.45768231[source]
In JavaScript, I really like const and have adopted this approach. There are some annoying situations where it doesn't work though, to do with scoping. Particularly:

- if (x) { const y = true } else { const y = false } // y doesn't exist after the block - try { const x = foo } catch (e) { } // x doesn't exist after the try block

replies(4): >>45768310 #>>45768515 #>>45768529 #>>45771225 #
NathanaelRea ◴[] No.45768310[source]
You could do an absolutely disgusting IIFE if you need the curly brace spice in your life, instead of a typical JS ternary.

  const y = (() => {
    if (x) {
      return true;
    } else {
      return false;
  })();
replies(2): >>45768491 #>>45768521 #
cookiengineer ◴[] No.45768491[source]
Technically you could just use an assignment ternary expression for this:

    const y = (x === true) ? true : false;
I used this kind of style for argument initialization when I was writing JS code, right at the top of my function bodies, due to ES not being able to specify real nullable default values. (and I'm setting apart why I think undefined as a value is pointless legacy).

    Composite.prototype.SetPosition(x, y, z) {

        x = (isNumber(x) && x >= 0 && x <= 1337) ? x : null;
        y = (isNumber(y) && y >= 0 && y <= 1337) ? y : null;
        z = isNumber(z) ? z : null;

        if x !== null && y !== null && z !== null {
            // use clamped values
        }

    }
replies(2): >>45768604 #>>45768832 #
1. fuzzythinker ◴[] No.45768832[source]
nitpick: cleaner w/o ()'s, as '=' is the 2nd lowest operator, after the comma separation operator.