I'm reading through https://markus.oberlehner.net/blog/using-the-google-maps-api-with-vue/ . In the section in the screenshot the author uses:
let initialized = !!window.google;
What does this mean?
I'm reading through https://markus.oberlehner.net/blog/using-the-google-maps-api-with-vue/ . In the section in the screenshot the author uses:
let initialized = !!window.google;
What does this mean?
window.google
either evaluates to something, or it evaluates to undefined
.
Before we get to your question, we need to look at the concept of "truthiness"
In JavaScript, a truthy value is a value that is considered true when encountered in a Boolean context. All values are truthy unless they are defined as falsy (i.e., except for false, 0, "", null, undefined, and NaN
Okay, back to your question. Let us assume it is something (a truthy value). !something
will evaluate to false. !false
evaluates to true, so !!something
will evaluate to true.
Assume now that it is undefined
. In this case !undefined
evaluates to true, then !true
evaluates to false. So, !!undefined
will evaluate to false.
In other words: if it is something (truthy), it is initialized. If not, then it hasn't been initialized.
So, !
before a truthy value (something) will make it false, then the extra !
negates that. Truthy things become true, and falsy things become false.
!! is a shorthand way of converting a variable into Boolean value. If google script is loaded correctly, window.google
would exist as an object
. !object
would return false
(if it is legit value, it is converted to true in Boolean checks in js, object is evaluated as true
, !true
is false
). Second not operating converts the false
back to true
, so object is converted into a Boolean value.
Same way, if there was error loading the script, then window.google
would be 'undefined', which is evaluated to be false
. using double not operating you convert undefined
into actual Boolean value false
.
!!expression
is a terse idiom to cast an expression's value to a Boolean.
In this case, initialized
will be set to true
or false
based on whether there's a global google
property with a truthy value.