Skip to content

Instantly share code, notes, and snippets.

@schnogz
Last active August 29, 2015 14:23
Show Gist options
  • Save schnogz/e942b514db987742c76f to your computer and use it in GitHub Desktop.
Save schnogz/e942b514db987742c76f to your computer and use it in GitHub Desktop.
Why semicolons should be used in JavaScript
// The following results in a syntax error.
var a = 'a'
[].forEach.call(document.querySelectorAll('.md'), function(e) {
console.log(e);
});
// Adding the semicolon and now everything works just fine.
var a = 'a';
[].forEach.call(document.querySelectorAll('.md'), function(e) {
console.log(e);
});
// Outputs:
// y00 d34d f00
// ¡Ay, caramba!
// Line 8 is unintentionally invoking function Y.
var Y = function () {
console.log('¡Ay, caramba!')
}
(function() {
console.log('y00 d34d f00')
}())
// adding the semicolon guards against the IIFE invoking the first function.
// Outputs:
// y00 d34d f00
var y = function () {
console.log('¡Ay, caramba!')
};
(function() {
console.log('y00 d34d f00')
}())
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment