Conditional If without logical comparison - I need to know what returns

Asked

Viewed 85 times

0

Good morning guys, I’m new to JS and would like to understand one thing. When we have an IF conditional on JS without a "Comparison" how does it work ? What does it return? The code interpreter enters this condition if it is what ?

I need to know what the IF parole returns so get on parole.

I’ll leave an example:

var supportsAudio = !!document.createElement('audio').canPlayType; if (supportsAudio){execução}

  • which is the next line after the if (supportsAudio) ? and why this assignment with double denial !!? That’s the same thing as simply var supportsAudio = document.createElement('audio').canPlayType;

  • It may also be useful: https://answall.com/q/315434/101 and https://answall.com/q/165494/101

  • 1

    The !! transforms the expression into boolean (see here), and then the if checks whether this value boolean is true. Complementing, within a if may have any value, which he uses those rules to determine whether it is true or false

1 answer

0

There seems to be a mistake in the way you’re interpreting the workings of if.

A structure if does not need to receive a comparison, it needs to receive a condition to be executed, usually true or false.

When you write a comparison within your condition if, you are not passing the comparison itself as a condition, but rather the result of the comparison.

Take the example

var i = 10;
if (i == 10) {
    // o resultado da comparação é true, por isso o código é executado

}

var j = 20;
var cond = j == 20; // o resultado da comparação é gerado nessa linha, ele é true
if (cond) {
    // como a condição do if é true, ele será executado
}

So in your example, what’s happening is that your condition is being generated through double negation !!.

The operator ! will deny the value returned from the method document.createElement('audio').canPlayType, result in true, or false, adding a second !, you deny the previous value. Why?

This can be useful when you are treating objects for example. The returned value of the negation of an object is false, while the negation of a value null is true.

So if you deny an object twice, your result will be true, while if you deny a value null twice, its result will be false.

In this way, its structure if will only be executed if the value that is in the variable is an object, that is, if the value is not null.

  • You do not need to delete the answer just because the question is marked as duplicate. Your answer is good.

Browser other questions tagged

You are not signed in. Login or sign up in order to post.