Why does window.something not cause an error?

I use the AdMob plugin in my Ionic application and one of the ways, as you can see in the documentation , to check if the plugin is loaded correctly:

if(AdMob) {
    ///other config code...
}

Now it works great on the device . However, it does not work in the browser ; it is an error in the console log: AdMob is not defined.

I found a solution to check for the existence of such a plugin (without error in the console):

if (window.AdMob){...}

And I saw this use on several issues here in StackOverflow. However, I could not find an explanation of why this does not cause an error.

I have an indefinite discussion of why this is so, but I would really appreciate it if someone experienced could explain this in more detail.

edit . I did additional tests as follows:

var a = "hi";
console.log(a); //shows "hi"
console.log(b); //throws an error that b is not defined

var c = {};
c.b = "hi again";
console.log(c.b); //shows "hi again" as expected

//and now for the grand finale
console.log(c.something);//doesn't throw an error, please explain to me in more detail why?
+4
source share
1 answer

I could not find an explanation of why this does not cause an error.

In the first example, you are trying to read the value of a full undefined identifier. In the second example, you are trying to read a property of an object that the object may not have.

undefined - ReferenceError; JavaScript , . , , undefined.

, , : " , , .

: typeof. undefined typeof:

if (typeof AdMob === "undefined")

ReferenceError, AdMob ; typeof "undefined". ( "undefined', AdMob undefined .)

:

... , .

ECMAScript, §6.2.3.1 ReferenceError §9.1.8 undefined , . , , 6- , .: -)

+4

Source: https://habr.com/ru/post/1628265/


All Articles