1

I know this might be a dumb question, but i spent quite some time and still cannot figure it out.

For sake of brevity, i created a simple demo:

$(function() {
  alert('hi, jQuery!')
  
  (function() {
    console.log('hi, IIFE')
  })()
})
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>

The alert work as expected, but console.log failed. More strangely, the error message logs:

Uncaught TypeError: alert(...) is not a function

Why did this even happen, as the alert statement was already executed?

Update

This question is due to lacking knowledge of how JS auto semicolon insertion(a.k.a ASI) works.

Refer JavaScript Semicolon Insertion - Everything you need to know for more detail.

Xlee
  • 3,543
  • 1
  • 19
  • 35
  • 2
    You missed `;` on the line `alert('hi, jQuery!');` – Quentin Roger Jan 23 '17 at 17:33
  • @Quentin Roger it seems fixed this demo, but should js runtime engine support leaving out `;`? – Xlee Jan 23 '17 at 17:35
  • 3
    @Xlee it does support it, but you need to understand what happens when you do. The error message is stating that the return of `alert(...)` is not a function (and it of course isn't.) – Kevin B Jan 23 '17 at 17:35
  • 2
    Remove the spaces after the alert() and you'll see: `alert()();` - `alert() is not a function` (it's not `alert is not a function`) – freedomn-m Jan 23 '17 at 17:37
  • 2
    related: http://stackoverflow.com/questions/17978883/what-is-the-purpose-of-a-semicolon-before-an-iife – Kevin B Jan 23 '17 at 17:38
  • For example, if you removed the `()` from around the iife and preceeded it with an operator, such as `+` or `!`, your code would work sans semi-colon https://jsfiddle.net/7rv3k617/. but that's nonsensical, just use a semi-colon. – Kevin B Jan 23 '17 at 17:42
  • @Kevin, great thanks for detailed explanation, i get the basics wrong. – Xlee Jan 23 '17 at 17:44
  • Your code is basically `var foo = alert("bar"); foo("world");` with the semicolon missing. Hence why it is important to use semicolons. – epascarello Jan 23 '17 at 17:45

0 Answers0