简体   繁体   中英

typeof of an object property (number) on passing to IIFE is returning undefined. Why?

How in the world the output is not number?

  • There is a simple function (IIFE) which is being passed an object, property of which is a number
  • When we are trying to find typeof of that property which refers to a number, the result is 'undefined'

How?

 <script> x = (function(foo){ return typeof(foo.bar); })({ foo: { bar: 1 } }); console.log(x); </script> 

If should be foo.foo.bar

foo parameter is an object with a property called foo in it

 x = (function(foo) { return typeof(foo.foo.bar); })({ foo: { bar: 1 } }); console.log(x); 

You probably meant to destructure the argument like this:

 x = (function({ foo }) { return typeof(foo.bar); })({ foo: { bar: 1 } }); console.log(x); 

foo is the argument. You have to access the properties inside the function using . notation

 x = (function(foo){ return typeof(foo.foo.bar); })({ foo: { bar: 1 } }); console.log(x); 

Your foo argument in your function is the entire object (not the nested one):

{ foo: { bar: 1 } }

So, when you do foo.bar there is no bar property, and so you get undefined .

Thus, typeof undefined will give you "undefined" . Instead, you can use clearer property names so the type of each object is easy to understand, and then access the foo property from your argument:

 x = (function(obj){ return typeof(obj.foo.bar); })({ foo: { bar: 1 } }); console.log(x); 

You can destructure foo in the function argument.

 let x = (function({foo}){ return typeof(foo.bar); })({ foo: { bar: 1 } }); console.log(x); 

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM