Beginner · Functions and closures · topic 11 of 61 · 25 min
Functions: declarations, expressions and return
Explanation
Why functions?
Imagine calculating GST in twenty places in an app. If the rule changes, you must find and fix twenty copies, and you will miss one. A function puts the rule in ONE place with a name. Every other part of the program calls the name. Functions also make code readable: calculateGst(price) explains itself.
Function declarations
function calculateGst(price, rate) {
return price * rate / 100;
}
console.log(calculateGst(1000, 18)); // 180
console.log(calculateGst(500, 5)); // 25A parameter is a name in the definition. An argument is the actual value passed in a call. Defining a function does not run it; calling it with brackets () runs it.
return
return does two things: it ends the function immediately, and it hands a value back to whoever called it. Code after a return that runs is never reached. A function with no return, or with a bare return;, gives back undefined.
function logTotal(a, b) {
console.log(a + b); // prints, but returns nothing
}
const result = logTotal(2, 3); // prints 5
console.log(result); // undefinedFunction expressions
A function is also a value. You can create one inside an expression and store it in a variable. This is a function expression. Unlike a declaration, it cannot be used before the line where it is created (module 5 explains this, called hoisting).
const square = function (n) {
return n * n;
};
console.log(square(9)); // 81
const tools = { square }; // stored in an object
console.log(tools.square(4)); // 16Functions are first-class values
First-class means functions can be treated like any other value: stored in variables, put in arrays and objects, passed as arguments to other functions, and returned from functions. This one idea powers callbacks, array methods like map, event handlers and closures.
Pure functions and side effects
A pure function always returns the same output for the same input and changes nothing outside itself. calculateGst is pure. A function that writes to a file, changes a global variable or prints has side effects. Programs need side effects, but keeping most functions pure makes them easy to test and reuse.
Need help?
Stuck on a word or an idea? Search this course, or every course, and jump straight to the explanation or a worked question.
Try:
Watch the lesson
Functions: declarations, expressions and return · 1/6
In this lesson you will write your own functions: named blocks of code you can reuse.
Prefer a video by a teacher? Find free videos on “javascript functions declaration expression return tutorial” on YouTube ↗
In real life: One discount rule for a whole shopping site
An e-commerce site applies a festival discount on product pages, in the cart and on the invoice. The rule lives in one function. When marketing changes the cap from ₹500 to ₹750, one line changes and every page is correct.
function festivalDiscount(price) {
const discount = price * 0.1;
return Math.min(discount, 500); // 10% off, at most ₹500
}
console.log(festivalDiscount(2000)); // 200
console.log(festivalDiscount(9000)); // 500Practice (0/3 done)
Write a function area(length, width) that returns the area of a rectangle.
showTotal(prices) only prints the total, so the rest of the program cannot use it. Rewrite it so it RETURNS the sum of the array.
Write a function applyTwice(fn, value) that calls fn on value, then calls fn again on the result, and returns that. Example: applyTwice(n => n + 3, 10) returns 16.
Quick quiz
Read more (free)
Related help
Before this, learn
This topic builds on these. If something here feels new, open them first.
Related topics
- Arrow functionsFunctions and closures · same module
- Parameters: defaults, rest and options objectsFunctions and closures · same module
- Scope and closuresFunctions and closures · same module
- Functions: declare, define, call and returnC++ Programming (modern C++ and DSA) · Decisions, loops and functions
- FunctionsFrontend Web Development · JavaScript basics
- Scope, hoisting and closuresFrontend Web Development · JavaScript in depth
Questions people ask about this
Open a question to see the answer and why. The first ones are this topic's own quiz, so try the quiz above before you peek.
What does a function return if it has no return statement?
Answer: undefined
Every JavaScript function without a return value gives undefined.
In function add(a, b) { … } and the call add(2, 3), what are a and b?
Answer: Parameters
Names in the definition are parameters; the values in the call are arguments.
function f() { return 1; console.log("hi"); } What happens when f() runs?
Answer: Returns 1 and never prints
return ends the function; the next line is never reached.
Which function is pure?
Answer: One that returns a * b
a * b depends only on its inputs and changes nothing outside.
What is a function prototype?Related
Answer: A declaration: the function's first line ending with a semicolon
It tells the compiler the function's name, return type and parameter types before its body appears.
What does a function return if it has no return statement?Related
Why can you call a function declaration above the line where it is written?Related
Answer: Hoisting: function declarations are ready before the code runs
JavaScript notes declarations before running. Function declarations are fully hoisted, unlike let and const.
Which function is pure?Related
Answer: (a) => a * 2
Only a * 2 depends only on its input and changes nothing.
Pass the quiz (60% or more) or mark this topic as done when you are ready.
Your progress is saved on this device only.
Next steps
- 4 more topics in “Functions and closures” before its exam: Arrow functions, Parameters: defaults, rest and options objects, Scope and closures, Higher-order functions and recursion.
- Module 3 exam: Functions and closures · 12 questions · 25 min, without help. 5 topics of this module still to finish first.
- Then the next module, Arrays and objects. 61 topics left in the course before the final exam.