4 ms·
You are correct that this is an issue when writing JavaScript without semicolons, but it's also an issue if you place an IIFE (immediately invoked function expr
by jacobwg 8y ago
You are correct that this is an issue when writing JavaScript without semicolons, but it's also an issue if you place an IIFE (immediately invoked function expression) directly after a function, even if you're using semicolons:
function hasSemicolons() {
console.log('hello world');
}
(function() {
console.log('this is broken, JS will call hasSemicolons()');
})()
In the ImmortalDB example, since it's a standalone <script> tag this is just extra defensive against a minifier that would join the tag with other tags, but just wanted to call out that there's a reason to include the leading semicolon in front of an IIFE whether or not you write your JavaScript with semicolons.
See also: https://stackoverflow.com/questions/1873983/what-does-the-leading-semicolon-in-javascript-libraries-do https://stackoverflow.com/questions/1873983/what-does-the-le...
- munk-a 8y agoThere is a reason why that issue with IIFEs can be hit, and it's because you've omitted some semicolons - granted they are the sort that most people omit. Since everything in js is a statement the correct semi-colon syntax for the above is function hasSemicolons() { console.log('hello world'); }; (function() { console.log('this is broken, JS will call hasSemicolons()'); })();
- recursive 8y agoThe ECMAScript specification (https://www.ecma-international.org/publications/files/ECMA-ST/Ecma-262.pdf https://www.ecma-international.org/publications/files/ECMA-S...) has statements in a separate chapter from function declarations. (Chapter 14) Furthermore, the function declaration grammar does not contain a semi-colon, unlike other statements.
- recursive 8y agoSo I tested this out in Firefox. I think you're wrong. I never see 'hello world' even if I remove all the whitespace between the functions.
- deleted 8y ago[deleted]
- arilotter 8y agoYour snippet doesn't fail. This one does console.log('this doesn't work!') (false ? console.log : console.error)('this will fail with a TypeError') >> Uncaught TypeError: console.log(...) is not a function console.log('this works!') ;(true ? console.log : console.error)('hello world')