How does the conditional operator work with a negation?

233 views Asked by At

I'm beginning to learn asynchronous javascript and, while I did understand callbacks and promises, something about the code I was learning got my attention. For example:

function funcA(){
    console.log('World')
}

function funcB() {
    return new Promise((resolve, reject) => {
        console.log('Hello')

        const error = false
        !error ? resolve() : reject('Error')
    })
}

funcB()
.then(funcA)
.catch(err => console.log(err))

In this case, isn't the !error saying if(error === true) then resolve it, and else (error === false), reject()?

Or it is simple saying "if there is no error, than resolve"?

1

There are 1 answers

5
FrostyZombi3 On BEST ANSWER

In the example code you provided, the line !error ? resolve() : reject('Error') would read "if not error, resolve, else reject with message 'Error'".

It is import to note the not operator(!) at the start of the line. This would be the equivalent to the following:

const error = false
if (!error) {
    resolve()
} else {
    reject('Error')
}