74

Is it possible to do something like this in JavaScript?

max = (max < b) ? b;

In other words, assign value only if the condition is true. If the condition is false, do nothing (no assignment). Is this possible?

4
  • 6
    Is there some reason for avoid using normal if statement? Commented Feb 21, 2013 at 18:03
  • 1
    max = (max < b) ? b : max ; Commented Feb 21, 2013 at 18:04
  • very hacky (max < b)?max = b:0; Commented Feb 21, 2013 at 18:07
  • What's wrong with an if statement? It expresses the intention clearly. Or, even better in this example, use Math.max(). Commented Feb 13, 2023 at 8:48

14 Answers 14

129

Don't use the ternary operator then, it requires a third argument. You would need to reassign max to max if you don't want it to change (max = (max < b) ? b : max).

An if-statement is much more clear:

if (max < b) max = b;

And if you need it to be an expression, you can (ab)use the short-circuit-evaluation of AND:

(max < b) && (max = b)

Btw, if you want to avoid repeating variable names (or expressions?), you could use the maximum function:

max = Math.max(max, b);
Sign up to request clarification or add additional context in comments.

3 Comments

The second one is faster the the first one? Because in terms of memory, seams to be the same amount used.
How about this: max < b ? b : null Is it exactly the same as the single line if, in terms of performance?
@UtkarshNarainSrivastava well that doesn't assign anything to max, and if behaviour is different then performance is irrelevant.
17

An expression with ternary operator must have both values, i.e. for both the true and false cases.

You can however

max = (max < b) ? b : max;

in this case, if condition is false, value of max will not change.

2 Comments

I'm curious... If the condition is false, under the hood, will it run an operation at all? Or will it replace itself.
I believe there are always to operations: eval the condition, then assign one of two different values. Of course the eval may result in many operations in itself.
11

You can just set max to itself if the condition is false.

max = (max < b) ? b : max;

Or you can try using the && operator:

(max < b) && (max = b);

Or to keep your code simple, just use an if.

if(max < v) max = b;

Comments

8

I think ternary is more suitable try this

(max < b) ? max = b : '';

Comments

5

Performace Results

As most of the answers pretty much tell you almost every possible method, here are some performance results for the four most common methods over 40 million iterations and an average of 10 runs each.

Using Ternary
For  a = b > a ? b : a the average time was 90.8ms for 40,000,000 iterations over 10 runs
Whereas for  (b > a) && (a = b) the average time was 88.7ms for 40,000,000 iterations over 10 runs

Using Math.max
for a = Math.max(a, b) the average time was 117.3ms for 40,000,000 iterations over 10 runs

Using an if statement
for if (b > a) a = b the average time was 88.9ms for 40,000,000 iterations over 10 runs

Hope this was interesting!

1 Comment

The results depend on a lot of factors (the CPU, the JavaScript interpreter, the version of the JavaScript interpreter etc) but this answer provides a very important conclusion: unless the code does the operation millions of times in a loop, performance-wise it does not matter which option one chooses. Let's choose the one that expresses the intention better. Let the code be clear and easy to read and understand. I would go with Math.max().
4

There isn't a specific operator that isn't the ternary operator, but you can use it like this:

max = (max < b) ? b : max;

Comments

2

I think a better approach could be

max = Math.max(max, b)

Comments

2

You can do something like this:

(max < b) ? max = b : ''

Comments

2

you can try:

(max < b) && (max = b);

look at this example:

let max = 10;
let b = 15;
(max < b) && (max = b)// this will be true
console.log("max=", max);

let maxx = 10
let bb = 5;
(maxx < bb) && (maxx = bb)// this will be false
console.log("maxx=", maxx);

1 Comment

Short-circuit evaluation, indeed must be the shorter snippet for the given problem
2

The ternary operator is used where we have a minimum of two possible outcomes.

let no = 10;
let max = 20;

max = no > max ? no : max

if you only want to use if, not else, then I recommend you to use if not the ternary operator.

let no = 10;
let max = 20;
    
if (no > max){
   max = no
}

if you want to use ternary operator, but don't want to use else part, then you may use this, but this won't be useful in every problem

let no = 10;
let max = 20;

no > max ? max = no : 0

here we are assigning value to a max variable only when the condition is true, otherwise, we are not doing anything

2 Comments

The behaviour of no > max ? max = no : 0 is difficult to understand. It is an expression whose value is not used but has side effects. The reader must make an effort to understand its purpose. Let the code be easy to read and understand. The computer does not care how the code looks like and the differences in performance are not important in 99.9% of the cases.
Agree, I was just telling the three different ways of doing one thing.
0

There was no example of ES6, we can use in this way:

let list = [{id: "abc", name: "test1"}, {id: "xyz", name: "test2"}]
let selectedData = {};
      list.some((exp) => {
        return (
          exp.id == "xyz" &&
          ((selectedData = exp), true)
        );
      })
console.log(selectedData);

Added description after a negative vote: Just adding a description to explain my solution. If you have an array of objects and you want if only one condition satisfies then we can use some. It will set the selectedData when the id == "xyz". As asked in the question, this will assign value only if the condition is true otherwise selectedData will be empty.

2 Comments

This was most likely downvoted as it didn't answer the original question. It was asked if there was a shorthand of an true ? true : original. The accepted answer is still the simplest and best answer, even for ES6!
Maybe it works but what is the human cost for it? The reader must know about and understand the meaning of the comma operator and the meaning of the assignment operator when it is used in an expression. More, they have to juggle with the possible values of exp.id == "xyz" struggling to understand when a value is assigned to selectedData and when the callback of Array.some() returns true and why. The code uses Array.some() for one of its implementation details (it stops on the first match) and not for its return value. In fact, it is a convoluted implementation of Array.find().
0

Instead of the ternary operator, you could use Logical AND assignment (&&=).

Basic examples

let output = false;
output &&= true;
console.log(output)

Reassignment is not possible because output has been defined as false.

const b = 10;
const max = 1;
let sum = max < b;

sum &&= 'new value';
console.log(sum);

Returns a string, because the variable sum has been defined as true.

1 Comment

While technically it works, it is a bad idea. The logical operators are meant to be used with logical values (true or false). JavaScript logical operators are loose, they accept values of any type and their results are of various, sometimes confusing types. Let the code express the intention clearly. In this question the intention is to keep the maximum value (probably of some values that are generated in sequence) in the max variable. The logical operators do not help understanding the intention, they divert the attention to unrelated flows and are possible cause of hidden errors.
0

when you want to assign only if condition to ternary in JavaScript then do following:

(condition) ? operation : void 0;

  • You have to pass else part otherwise JavaScript interpreter will throw error.
  • void 0 will return undefined
  • It'll be okay to use "null" instead

Comments

-1

(A different way) To make the answer more complicated & useless...::

      // ;M1;
      let max = 99;
      let b1 = 50;
      let b2 = 100;
      let max_ori = max;
      max = (max < b1) && b1;
      max ||= max_ori;
      expect(max).toEqual(99);
      max = (max < b2) && b2;
      max ||= max_ori;
      expect(max).toEqual(100);
      // ;M2;
      max = 99;
      b1 = 50;
      b2 = 100;
      max = ((max < b1) && b1) || max;
      expect(max).toEqual(99);
      max = ((max < b2) && b2) || max;
      expect(max).toEqual(100);

JavaScript || or operator with an undefined variable

The logical OR assignment (x ||= y) operator only assigns if x is falsy.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_OR_assignment

returning immediately with the value of the first falsy operand it encounters; if all values are truthy, the value of the last operand is returned.

https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Logical_AND

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.