JavaScript Tutorial · Functions · Lesson 18 of 44

JavaScript Functions

Declare functions, pass arguments and return values.

Declaring a function

A function is a reusable block of code. Declare it with function, then call it with parentheses:

Example 1Try it yourself
function greet(name) {
  console.log(`Hello, ${name}!`);
}
greet("Ada");
greet("Linus");

Output

Hello, Ada!
Hello, Linus!

Return values

return sends a value back to the caller and ends the function. A function without return returns undefined.

Example 2Try it yourself
function add(a, b) {
  return a + b;
}
function logOnly(x) {
  console.log("got", x);
}
const sum = add(2, 3);
console.log(sum);
console.log(logOnly(1));

Output

5
got 1
undefined

Function expressions

Functions are values: you can store them in variables, pass them to other functions and return them.

Example 3Try it yourself
const square = function (n) {
  return n * n;
};
function applyTwice(fn, value) {
  return fn(fn(value));
}
console.log(square(4));
console.log(applyTwice(square, 3));

Output

16
81

Function declarations are hoisted — you can call them before the line where they're defined. Function expressions assigned to const are not.

Test yourself

What does a function return if it has no return statement?

  1. null
  2. 0
  3. undefined
  4. false
Show answer

Answer: undefined