Skip to content
Programming contents

Lesson 1.10: Functions in JavaScript

The functions from 1.6, written in JavaScript: function to define one and return to give back a result.

The idea

PseudocodeJavaScript
Function double(number)function double(number) {
Return number * 2return number * 2;
EndFunction}
JavaScript
function double(number) {
  return number * 2;
}

console.log(double(4));
console.log(double(10));
Console
8
20

Several parameters

Separated by commas, like in pseudocode:

JavaScript
function area(base, height) {
  return base * height;
}

console.log(area(3, 4));
Console
12

Without return

A function can also do something without returning anything:

JavaScript
function greet(name) {
  console.log("Hello, " + name);
}

greet("Ana");
Console
Hello, Ana

If you use its result, you'll see undefined: that's JavaScript's word for "no value".

The short form

In other people's code you'll see functions written with an arrow, =>:

JavaScript
const double = (number) => number * 2;

It does the same as the one above. Here we use function until writing functions feels natural.

Try it

Exercise

Write a function isEven(n) that returns true if n is even and false if it isn't. Hint: the % from 1.8.

Show the solution
JavaScript
function isEven(n) {
  if (n % 2 === 0) {
    return true;
  } else {
    return false;
  }
}

Since n % 2 === 0 is already true or false, you can return it directly:

JavaScript
function isEven(n) {
  return n % 2 === 0;
}

Summary

  • function defines a function; return gives back the result and ends it.
  • Without return, the function returns undefined.
  • The arrow => is another way to write them.