Contrary to what people believe if
just decides to do something if it has a real value, or does nothing or falls into the else
if it has a false value. This thing has a condition in the if
is an invention of people’s heads, it only deviates the flow of execution conditionally according to a value, and this value must be boolean, nothing more than that. In fact, most of the time, people put an expression there that results in a boolean, but that’s a coincidence. You could do that:
if (true) console.log("ok");
And this block would always run because it’s always true, of course it doesn’t make sense because it’s a conditional that you already know the result.
You can make a code like this:
var variavel = true;
if (variavel) console.log("ok");
Now it makes more sense because it has a variable that is worth a boolean, but it still doesn’t make much sense because you know the value of this variable, it would make more sense if it’s a variable that you don’t have as much control over. This is the case of the variable elem.requestFullscreen
. He certainly is worth true
or false
and you don’t know what it is, so you can get into if
or not.
Another way that people don’t understand would be something like this:
var entrada = prompt("digita a");
var variavel = entrada == "a";
if (variavel) console.log("ok");
I put in the Github for future reference.
Realized that now you don’t have the control if you will run the block if
or not? And I used a variable to establish the condition, I did not if
. It doesn’t make much sense to have this variable, I just did so to demonstrate that the condition does not belong to the if
, you can make it anywhere you expect an expression and preferably somewhere you expect a boolean result since the operator ==
comparison, just like other comparison operators, always result in a boolean (true
or false
). Relational operators also result in a boolean, and some functions as well, and some object properties hold boolean.
In summary the if
expects a boolean and the variable you used is a boolean "per table" (I explain below), and there the decision is made whether it is executed or not. So in your example if the property pro requestFullscreen
is true, ie, I understand that it indicates that it is allowed to order to stay in full screen (even if implicitly), it calls the method that makes stay full screen.
In this specific case requestFullscreen
is a function, if it exists it assumes the value true
where one expects a boolean (Javascript has weak typing, this is a curse because it happens a lot of weird thing, but gives this flexibility), and if the function does not exist it assumes false
, so I wouldn’t be in if
, after all if the function does not exist should not execute it. This is called progressive improvement.
Then in this case if the browser has the ability to perform function to put in full screen it will run, otherwise nothing will be done. If you don’t use the if
there will be a mistake.