Search code examples
javascripthtmliife

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>


Solution

  • 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);