Introduction to Functions in JavaScript
A function is a named block of code that runs when you call it. You write the steps once, and then run them as many times as you need by writing the function’s name followed by parentheses.
function name() { // statements to run}
name();Declaring and calling a function
Section titled “Declaring and calling a function”A function declaration starts with the function keyword, then the name, a pair of parentheses and a body in braces. Declaring the function does not run it, because the body runs only when the function is called.
function printHeader() { console.log('Shopping list'); console.log('-------------');}
printHeader();console.log('Bread');printHeader();console.log('Apples');This prints:
Shopping list-------------BreadShopping list-------------ApplesThe two lines of the header are written once, so a change to the header needs one edit rather than one per copy.
Functions that change outside variables
Section titled “Functions that change outside variables”A function body can read and change variables declared outside it. Here each function adds the price of one item to a running total:
let basketTotal = 0;
function addBread() { basketTotal += 1.45; console.log(`Total: £${basketTotal.toFixed(2)}`);}
function addMilk() { basketTotal += 0.95; console.log(`Total: £${basketTotal.toFixed(2)}`);}
addBread();addMilk();addMilk();This prints:
Total: £1.45Total: £2.40Total: £3.35The two functions are identical apart from the price, which is a sign that one function should take the price as an input. Function Parameters shows how. Functions that change shared variables are also harder to test than functions that take inputs and return a result, so keep this style for small scripts.
Declarations and expressions
Section titled “Declarations and expressions”A function can also be created as an expression and stored in a variable. The two forms behave the same when called, but they differ in when the function becomes available. A declaration is hoisted, so it can be called earlier in the code than the line that declares it. A function expression exists only once the line that assigns it has run.
sayHello();
function sayHello() { console.log('Hello from a declaration');}
const sayGoodbye = function () { console.log('Goodbye from an expression');};
sayGoodbye();console.log(typeof sayGoodbye);This prints:
Hello from a declarationGoodbye from an expressionfunctiontypeof reports function, because a function is a value like a number or a string. It can be stored in a variable, kept in an array or passed to another function, which the later pages in this section rely on.
Calling an expression before its line runs fails, because a const or let variable cannot be read before it is initialised:
try { sayGoodbye();} catch (error) { console.log(error.message);}
const sayGoodbye = function () { console.log('Goodbye');};This prints:
Cannot access 'sayGoodbye' before initializationHoisting in JavaScript covers the rules in detail.
Naming functions
Section titled “Naming functions”JavaScript functions are usually named in camelCase with a verb first, such as printHeader or calculateTotal, so the name says what calling the function does. Names with underscores, such as add_bread, are legal but are not the usual JavaScript style.
Steve Griffith covers this topic in his video Introduction to Functions in JavaScript.