ROUND ONE - LOOKS (CAN BE DECEIVING)
Our competitors may look alike, but the function statement has two distinguishing characteristics: the declarative keyword function always comes first, and you must name it. Here’s what it looks like:
Pull back the curtain, though, and the function statement expands into a variable with a function value:
Absent the mark of the function statement, you have the function expression. The function expression is optionally named (but normally anonymous), e.g.:
1 2 3 4 5
WINNER: Function Expression. Crockford’s manual argues the case for clear code. The function expression is clearly recognisable as what it really is (a variable with a function value).
ROUND TWO - (UNPREDICTABLE) BEHAVIOUR
Variables are subject to a thing called hoisting. Irrespective of their apparent place in the flow of things, their var part is removed and hauled to the top of a containing (whether function or global) scope, and initalised with
1 2 3 4 5 6
The function statement - while just shorthand for a var statement with a function value - is treated differently: the whole lot is hoisted. For this reason, you can call a function statement before you have declared it in your code:
1 2 3 4 5 6 7 8 9 10
WINNER: Function Expression. Hoisting is already a behind-the-scenes behaviour that can cause head scratching. The particular behaviour of the function statement can lead to more furious head scratching.
ROUND THREE - SUPER POWERS
The function statement is widely used and performs just fine, but it has an obvious limitation: You can’t immediately invoke it.
The function expression is more flexible, e.g.:
1 2 3 4
Parentheses are required to nudge
function out of statement position (can’t immediately invoke), and into expression position (can immediately invoke). Crockford recommends grouping the entire invocation inside parentheses for clarity - what’s important here is the product of the invoked function - otherwise, Crockford argues, “you’ve got these things hanging outside of it looking like dog balls.”
WINNER: Function Expression.
FINAL SCORE: Function Expression Wins 3 - 0
CONCLUSION - I HEART A GOOD MANUAL
Today’s smackdown was inspired by Andrew Torba’s Startup Smackdown: Treehouse vs. Codecademy