0

Can't seem to figure out why its not able to access variable 'a':

var a = function(){
    console.log('AAA');
}
(function(){
    console.log(a);
})();
Patrick Roberts
  • 49,224
  • 10
  • 102
  • 153
Jp Mohan
  • 160
  • 2
  • 7
  • Why isnt it? ... – Jonas Wilms Feb 21 '18 at 15:11
  • 4
    Your code is missing a semicolon after the value of `a`. – Pointy Feb 21 '18 at 15:11
  • 4
    Add a semicolon. You're executing the first function and passing the second function as an argument. Then it throws an error when you try to invoke `undefined` since there's no return value. – Patrick Roberts Feb 21 '18 at 15:12
  • One of the many quirks of JavaScript. Wasn't [the newline supposed to end the statement](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Basics)? – axiac Feb 21 '18 at 15:35

3 Answers3

2

The problem here is that you're trying to call a function as follow undefined(), Why?

This is what is happening:

var a = function(){
    console.log('AAA');
}(...) //<- here you're calling the function `a`, but your function `a` doesn't return anything (`undefined`)

You can solve this adding a semi-colon:

var a = function(){
    console.log('AAA');
}; //<- HERE!

(function(){
    console.log(a);
})();

Or, you can declare the function a as Declaration rather than as Expression

Take at look at this Question to understand a little more.

function a(){
    console.log('AAA');
}

(function(){
    console.log(a);
})();

Resource

Ele
  • 33,468
  • 7
  • 37
  • 75
0

Actually you build an IIFE. What that means is that:

 var a = function(){
    console.log('AAA');
}
()

Actually calls the function, and stores its result in a. If you put a function into that function call as an argument, it goes into nowhere as the first function accepts no parameter.

Arnav Borborah
  • 11,357
  • 8
  • 43
  • 88
Jonas Wilms
  • 132,000
  • 20
  • 149
  • 151
  • I would upvote because your answer explains the problem, but it's technically incorrect, saying `and stores its result in a`. The assignment is never reached since there's two chained invocations: `var a = function () { ... }(...)()` which is why the snippet in the question throws an error. – Patrick Roberts Feb 21 '18 at 15:17
-1

var a = function(){
    console.log('AAA');
};
(function(){
    console.log(a);
    a();
}());
FarukT
  • 1,560
  • 11
  • 25