Skip to content

Instantly share code, notes, and snippets.

@armstnp
Last active March 19, 2018 14:44
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save armstnp/0bffdaf49891f896b5c05b3383479a4a to your computer and use it in GitHub Desktop.
Save armstnp/0bffdaf49891f896b5c05b3383479a4a to your computer and use it in GitHub Desktop.
A Javascript Mystery...
var inlineArrowFunc = (x, y) => true;
var multilineArrowFunc = (x, y) => {
console.log(x);
return x + y;
};
var objectLiteral = { content: true };
gotoLabel:
// Now here's the puzzle: What is this?
var mysteryBox = (x, y) => { content: x + y };
// If you guessed 'a function that returns an object literal', you're wrong!
// If you guessed 'syntax error', you're wrong!
// If you guessed 'linter error', you're wrong!
// If you guessed 'a function that has a label with the symbol `content`,
// evaluates and discards the expression `x + y`, and then returns `undefined`,
// you're right and also probably suicidal by this point.
// Syntax overloading kills, folks!
// Oh, and object literals with multiple properties?
var brokenMysteryBox = (x, y) => { a: x, b: y };
// --> Uncaught SyntaxError: Unexpected token :
// Wrapping the literal in parentheses forces it to be parsed as an expression.
var wrappedLiteral = (x, y) => ({ content: x + y });
// Using block syntax explicitly prevents the inner object's braces
// from being parsed as a block.
var blockArrowLiteral = (x, y) => { return { content: x + y }; };
// Thanks to Luke Willis: ESLint rules to help catch this when it occurs
{
"rules": {
"no-labels": ["error", { "allowSwitch": true }],
"semi": "error" // optional, my preference
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment