Conditional assign operator

# Sultan (4 years ago)

The following would assign to the address foo in obj if and only if it has not already been assigned.

var obj = {} var foo = Math.random() obj[foo] ?= 1

The same can be said for:

var undef undef ?= 1

Which could both be transpired to

type obj[foo] === 'undefined' && obj[foo] = 1

or

type a === 'undefined' && undef = 1

respectively.

# 森建 (4 years ago)

See Stage 3 Logical Assignment Proposal. tc39/proposal-logical-assignment

Thanks. 2020年4月13日 18:17 +0900、Sultan <thysultan at gmail.com> のメール:

# Jordan Harband (4 years ago)

Are you familiar with tc39/proposal-logical-assignment ?

# Bob Myers (4 years ago)

What I've long wanted is an assignment operator which evaluates to the pre-assignment value of the LHS. You know, sort of like a++ evaluates to the pre-incremented value of a. We could call this this "post-assignment" operator. Has anyone ever proposed that?

let a = 1;
console.log(a =^= 2); // logs 1 and then sets a to 2
# Bergi (4 years ago)

What I've long wanted is an assignment operator which evaluates to the pre-assignment value of the LHS. You know, sort of like a++ evaluates to the pre-incremented value of a.

Given the amount of confusion that the difference between ++a, a++ (and a += 1) already has caused, I doubt that would be a good idea. In most, if not all, cases the desired behaviour can be easier and cleaner expressed with two statements, and a temporary variable if absolutely necessary.

let a = 1;
console.log(a =^= 2); // logs 1 and then sets a to 2

would be just

let a = 1;
console.log(a)
a = 2;

kind , Bergi

# Naveen Chawla (4 years ago)

Yes I like syntactic sugar when it doesn't sacrifice clarity (e.g. class, arrow functions).

However, I do like the logical assignment operator pointed out by Jordan somewhat more than the "conditional assign" ("if not assigned") idea at the beginning of this thread. My reason is that you cannot "reset" a variable to a "not assigned" state to re-use the "conditional assign" operator, whereas you can reset a variable to a nullish or falsy state and re-use the logical assignment operator, e.g.

x ||= 5; x = null; //this works as a reset!

x ?= 5; x = undefined; //this doesn't work as a reset! Apparently nothing will

However, maybe non-resettability is a desired feature of the conditional assign operator idea, so maybe it should be an additional feature, albeit with different syntax