JavaScript course menu
JavaScript Functions: Declaring, Calling and Returning Values
Learn JavaScript functions: function declarations, parameters and arguments, return values, undefined when nothing is returned, function expressions, functions as values, pure functions, and how to name and design small functions.
On this page
A function is a named, reusable block of code. You define it once and call it whenever you need it, possibly with different inputs each time. Functions are the main way to organise JavaScript programs.
Declaring and calling#
function greet() {
console.log("Welcome to Laviyx Learn!");
}
greet();
greet();Welcome to Laviyx Learn!
Welcome to Laviyx Learn!function greet() { ... }declares the function. Nothing runs yet.greet()calls it. The parentheses are what make it run.
Parameters and arguments#
Functions become useful when they take inputs. Parameters are the names in the definition; arguments are the values passed in a call:
function greet(name, course) {
console.log(`Hi ${name}, welcome to the ${course} course!`);
}
greet("Asha", "JavaScript");
greet("Ravi", "CSS");Hi Asha, welcome to the JavaScript course!
Hi Ravi, welcome to the CSS course!Missing arguments become undefined, and extra ones are ignored:
function show(a, b) {
console.log(a, b);
}
show(1);
show(1, 2, 3);1 undefined
1 2Default values for missing parameters are covered in Parameters, Defaults and Rest.
Returning a value#
return sends a value back to the caller and ends the function:
function gst(price) {
return price * 0.18;
}
const tax = gst(500);
console.log(tax);
console.log(gst(1000) + gst(200));90
216A call is an expression, so you can store its result, print it or use it in a calculation.
A function without a return (or with a bare return;) returns undefined:
function logOnly(x) {
console.log("logging", x);
}
const result = logOnly(5);
console.log(result);logging 5
undefinedCode after a return in the same block never runs.
Function expressions#
Functions are values. You can store one in a variable:
const square = function (n) {
return n * n;
};
console.log(square(7));
console.log(typeof square);49
functionThe shorter arrow function syntax, const square = (n) => n * n;, is covered in Arrow Functions.
One difference: function declarations are hoisted, so you can call them before the line where they are written. Function expressions stored in const cannot be used before that line. See Scope and Hoisting.
Functions as values#
Because functions are values, you can pass them to other functions, which is how much of JavaScript works:
function applyTwice(fn, value) {
return fn(fn(value));
}
function double(n) {
return n * 2;
}
console.log(applyTwice(double, 5));20Note: double (without parentheses) is the function itself; double(5) calls it. This idea is developed in Callbacks and Higher-Order Functions.
Designing good functions#
- Do one thing.
calculateTotalandformatPriceare better than onecalculateAndFormatAndPrint. - Name with a verb:
getUser,isValidEmail,sendInvite. - Prefer returning values over printing inside the function, so the result can be reused.
- Pure functions, whose output depends only on their inputs and which change nothing outside themselves, are the easiest to test and reason about.
// Pure: same input, same output, no side effects
function totalWithTax(price, rate) {
return price + price * rate;
}
console.log(totalWithTax(200, 0.05));210Practice#
Practice exercise
Write a function isEven(n) that returns true or false, and a function countEvens(numbers) that uses it to count the even numbers in an array. Test with [3, 8, 10, 15, 22].
Show solution
function isEven(n) {
return n % 2 === 0;
}
function countEvens(numbers) {
let count = 0;
for (const n of numbers) {
if (isEven(n)) count++;
}
return count;
}
console.log(isEven(4), isEven(7));
console.log(countEvens([3, 8, 10, 15, 22]));true false
3Key takeaway#
Finished this lesson?