2

Here is the code

var numberArray = [0, 1]

(function() {
  numberArray.push(2)

  function nestedFunction() {
    numberArray.push(3)

    function anotherNestedFunction() {
      numberArray.push(4)
    }

    console.log(numberArray)
  }
})()

I am expecting numberArray with value [0,1,2,3,4] but it is giving this error:

TypeError: [0,1] is not a function

Sebastian Simon
  • 18,263
  • 7
  • 55
  • 75
Saurabh
  • 1,592
  • 2
  • 14
  • 30
  • 3
    Put a semicolon at the end of the `var` line. – Sebastian Simon Aug 30 '18 at 08:52
  • 3
    Possible duplicate of [Immediately invoked function expression throws "object is not a function"](https://stackoverflow.com/questions/21031820/immediately-invoked-function-expression-throws-object-is-not-a-function) – Sebastian Simon Aug 30 '18 at 08:53

2 Answers2

4
var numberArray = [0, 1]
(function() {

is equivalent to

var numberArray = [0, 1] (function() {

That is where the error rise.

To resolve the issue place ; after the array declaration which JavaScript engine will consider both the line as separate statement:

var numberArray = [0, 1];

(function() {
  numberArray.push(2);

  function nestedFunction() {
    numberArray.push(3);

    function anotherNestedFunction() {
      numberArray.push(4);
    }
    
    anotherNestedFunction();
    console.log(numberArray);
  }
  nestedFunction();
})();

To ignore all these unexpected issue, it is always good practice to use semicolons (;) after every statement in JavaScript.

Mamun
  • 66,969
  • 9
  • 47
  • 59
  • 1
    Good to know why I'm using semicolons at the end of every line in JS :D (I just knew it could cause issues, but I've never seen an actual case of it) – d0n.key Aug 30 '18 at 10:36
1

Here is a working snippet

const numberArray = [0, 1];

(function() {
  numberArray.push(2);

  (function nestedFunction() {
    numberArray.push(3);

    (function anotherNestedFunction() {
      numberArray.push(4);
    })();

    console.log(numberArray);
  })();
})();

If you remove the ; after numberArray this is where you got a problem. You also have to use IIFE with your inner declared functions.

const numberArray = [0, 1]

(function() {
  numberArray.push(2);

  (function nestedFunction() {
    numberArray.push(3);

    (function anotherNestedFunction() {
      numberArray.push(4);
    })();

    console.log(numberArray);
  })();
})();
Orelsanpls
  • 22,456
  • 6
  • 42
  • 69