Welcome!

By registering with us, you'll be able to discuss, share and private message with other members of our community.

SignUp Now!
  • Guest, before posting your code please take these rules into consideration:
    • It is required to use our BBCode feature to display your code. While within the editor click < / > or >_ and place your code within the BB Code prompt. This helps others with finding a solution by making it easier to read and easier to copy.
    • You can also use markdown to share your code. When using markdown your code will be automatically converted to BBCode. For help with markdown check out the markdown guide.
    • Don't share a wall of code. All we want is the problem area, the code related to your issue.


    To learn more about how to use our BBCode feature, please click here.

    Thank you, Code Forum.

JavaScript Using conditions for assignments

name-taken

New Coder
Hello everyone!

I was messing around with using conditionals to assign values to variables and see up to which point could I simplify the code to a single line.

I'm just checking for the maximum and the minimum values from a set by using a forEach.

One solution would be to do this:

JavaScript:
let max = Number.MIN_VALUE,
    min = Number.MAX_VALUE;

set.forEach((num) => {
    num > max && (max = num);
    num < min && (min = num);
}

Now, obviously if statements could do this clearer, but I wanted to see if I could do this in with a one-liner approach. This was my initial attempt:

JavaScript:
let max = Number.MIN_VALUE,
    min = Number.MAX_VALUE;

set.forEach((num) => num > max && (max = num) && num < min && (num = min));

This works for the most part, except when dealing with negative numbers. I swapped the connector AND with an OR:

JavaScript:
let max = Number.MIN_VALUE,
    min = Number.MAX_VALUE;

set.forEach((num) => (num > max && (max = num)) || (num < min && (min = max)));

However, this didn't quite work. Now, this is extremely weird to me as this is the only language I've seen where you can use conditionals like this to assign to a variable. From a Boolean algebra standpoint, I do not how this is really being evaluated. Upon which conditions?

Anyway, I tried every possible way to see if I could get it working, and I did. But by negating the assignments:

JavaScript:
set.forEach((num) => (num > max && !(max = num)) || (num < min && !(min = num)));

Can someone provide some input to how this works? How is this being evaluated? How come negating the assignments work? I just can't wrap my head around this...
 
Last edited:

New Threads

Buy us a coffee!

Back
Top Bottom