2

I am new to Javascript and I'm trying to understand what IIFEs are. I saw the example below on youtube it worked well on the video but when I tried to do the same thing I got an error like

Uncaught TypeError: 4 is not a function

the code:

var a = 4

(function(){
    var a = 5
    console.log(a)

})()

console.log(a)

I searched google but I couldn't find an answer.

Not A Bot
  • 2,474
  • 2
  • 16
  • 33
Erenay Ata
  • 21
  • 2
  • 2
    It's because you're missing a semicolon after the `4`. As a result, you've basically written `var a = 4(/*...function here...*/)()`, and as the error says, `4` isn't a function, but `4(/*...*/)` tries to use it as one. – T.J. Crowder Feb 15 '23 at 07:15
  • but my instructor said we don't have to use semicolons in javascript it's optional – Erenay Ata Feb 15 '23 at 07:17
  • Semicolons are optional (before a newline) ***IF*** the absense of a semicolon doesn't change the meaning of the code by letting the parser think the expression/statement continues with the code on the next line. In this example, it does change the meaning of the code, so the semicolon is mandatory. If your instructor didn't teach you that, you might need to take other things the instructor tells you with a grain of salt. – T.J. Crowder Feb 15 '23 at 10:40
  • Simpler example: `4-1` vs. `4;-1`. The former is a subtraction expression spanning lines; the latter is two isolated expression statements. In general, if you're going to leave out semicolons, you need to put a semicolon at the beginning of any line starting with `(`, `[`, or a unary operator with a binary synonym (`+`, `-`, ). Or (to my way of thinking) just write semicolons at the ends of statements rather than trying to box clever. – T.J. Crowder Feb 15 '23 at 10:43
  • Be aware that [Automatic Semicolon Insertion](https://tc39.es/ecma262/multipage/ecmascript-language-lexical-grammar.html#sec-automatic-semicolon-insertion) (as it's called) is an *error correction feature* of the JavaScript parsing specification. Statements are expected to end with semicolons, but when it can without changing the meaning of the code, the parser will insert missing ones for you. – T.J. Crowder Feb 15 '23 at 10:54

1 Answers1

-1

just add ; between 4 and ( for example:

var a = 4; // <---- add to this

(function(){
    var a = 5
    console.log(a)

})()

console.log(a)

if you don't have it the browser will remove that space and become 4(...) i.e. you are calling a function called 4 with a function parameter

Tachibana Shin
  • 2,605
  • 1
  • 5
  • 9