Module 4: Functions, Scope, and Closures
Function Declarations and Expressions
Define reusable behaviour and understand the basic differences between function forms.
Functions package behaviour so it can be called with different inputs. A function declaration defines a named function:
function add(a, b) {
return a + b;
}
console.log(add(2, 3)); // 5
A function expression assigns a function value to a variable:
const multiply = function (a, b) {
return a * b;
};
Function declarations are initialized during their scope's setup, so they can generally be called before their textual declaration. A const function expression cannot be accessed before its initialization.
Return values#
A function without an explicit return produces undefined. return exits the current function and sends a result to the caller. Logging a value is not the same as returning it.
function double(value) {
return value * 2;
}
const result = double(4);
Design small functions#
A good function usually has a clear responsibility, meaningful parameters, and a predictable return value. Keep unrelated side effects separate when practical. Avoid depending on global variables if the needed value can be passed as an argument.
Practice#
Create a calculateTotal function that receives price and quantity and returns their product. Then call it with several different inputs.