Variable reassignment with chained booleans or ternary operator [closed]

Tags: , ,



To clarify:
This is purely for experimental purposes, to learn the quirks, odds and ends of a new (to me) language. I would of course write it readable if I ever were to share this code with anyone else. 🙂


I have a function someFunction(x), and two global variables:

let m = 2;
let e = 5;

Inside the function, I want to check if x == m. If this is true, I’d like to pass m to a side function call (sideFunction(m)), then reassign x to e to complete someFunction.

This does work as expected:

const someFunction = x => {
    if (x == m) {
        sideFunction(m);
        x = e;
    }
    doOtherStuffWith(x);
}

However, I’d like to shorten it, preferably to one line. This is also to understand more about ternaries and/or boolean chaining.

I have tried these two methods:

// Boolean chaining
const someFunction = x => {
    x == m && sideFunction(m) && (function () {x = e})();
    doOtherStuffWith(x);
}

This does not work, presumably because the assignment x = e only applies to the x in the local scope of the inner, anonymous function…?

// Ternary operator
const someFunction = x => {
    x = (x == m && sideFunction(m)) ? e : x;
    doOtherStuffWith(x);
}

This does not work, presumably because sideFunction(m) doesn’t actually get called, for some reason…?

How can I fix these to make them work?
Alternatively, are there other, elegant ways to perform this check/call/reassignment without a full multi-line if block?

Thank you very much!

Answer

The problem with

x == m && sideFunction(m) && (function () {x = e})();

is that && evaluates left-to-right, and will stop as soon as the first falsey value is found. Unless sideFunction returns something explicitly truthy, the third IIFE:

(function () {x = e})()

will never run, resulting in x never being reassigned.

x is local in that function. If you can get the function to run, it will reassign x as desired.

You could use the comma operator:

x == m && (sideFunction(m), x = e);

Similarly

x = (x == m && sideFunction(m)) ? e : x;

won’t work because sideFunction would have to return something truthy for the left side of the conditional to evaluate truthily – otherwise, x will be assigned to x, no change.


All this said – I’d highly recommend not doing any of these. Your first approach is much more readable, and readability is much more important than line conservation.



Source: stackoverflow