From "You Don't Know JS: Types & Grammar"
🎧 Listen to Summary
Free 10-min PreviewFunctions in JavaScript
Key Insight
In JavaScript, a 'function' refers to a procedure: a collection of statements executable multiple times, potentially receiving inputs and yielding outputs. Functions can be defined through a 'function declaration,' which is a standalone statement (e.g., 'function awesomeFunction(coolThings) { return amazingStuff; }'), associating the identifier with the function value during compilation. Alternatively, a 'function expression' is defined and assigned to a variable, with its association occurring at runtime (e.g., 'var awesomeFunction = function(coolThings) { return amazingStuff; };').
A fundamental aspect of JavaScript is that functions are values, allowing them to be assigned to variables, passed as arguments, and returned from other functions; they are specifically a sub-type of object value. Functions accept input via parameters, acting as local variables within the function's scope, where each parameter receives an argument value passed during invocation, as in 'function greeting(myName) { console.log(`Hello, ${ myName }!`); } greeting("Kyle");'. Functions can also return a single value using the 'return' keyword, or multiple values if bundled into an object or array.
Functions can be assigned as properties on objects, enabling method-like behavior. For example, an object 'whatToSay' can contain functions like 'greeting()', 'question()', and 'answer()', accessed and invoked via 'whatToSay.greeting()'. This capability underscores JavaScript's support for flexible programming patterns, including functional programming, by treating functions as first-class citizens in the language.
📚 Continue Your Learning Journey — No Payment Required
Access the complete You Don't Know JS: Types & Grammar summary with audio narration, key takeaways, and actionable insights from Kyle Simpson.