Can I assign a value to a variable within a AND / OR sentence

37 views Asked by At

I haven't been able to find the keywords to find this question, because this has obviously been already answered, so I can only ask it again:

Can I assign a value to a variable like this? How could I express it to keep the one-line structure?

let found = false
if (1) console.log('hi') && (found = true)
console.log(found) // it is still false

The real code is something like that

array.map(e => 
  condition_is_meet_with_e && 
  put_variables_in_a_complex_structure && 
  flag_that_the_condition_has_been_fulfilled <<== found = true
)
1

There are 1 answers

0
GWorking On

Apparently it works, but somehow console.log returns a false?

So, in this specific example, this is what works

let found = false
if (1) console.log('hi') || (found = true)
console.log(found) // it is now true

And anything else should work as expected

let found = false
let what = 1
console.log(found) // false
if (1) (what = 2) && (found = true)
console.log(found) // true