JavaScript Basics: Make Web Pages Come Alive · Lesson 6 of 8

Lesson 6: Functions

Group code into reusable functions, pass values in, return results, and write short arrow functions.

Lesson 6: Functions

A function is a named block of code you can run again and again. You already used console.log(); now you will write your own.

function greet(name) {
  return `Namaste, ${name}!`;
}
console.log(greet("Sita"));
console.log(greet("Hari"));

Output:

Namaste, Sita!
Namaste, Hari!

Values go in through parameters (name) and come back out with return.

function area(length, width) {
  return length * width;
}
console.log(area(12, 9));
console.log(area(3, 4) + area(2, 2));

Output:

108
16

Arrow functions

A shorter way to write functions. For one-line functions the return is implied.

const double = n => n * 2;
const add = (a, b) => a + b;
console.log(double(21));
console.log(add(5, 7));

Output:

42
12

Default values

function priceWithTax(price, rate = 13) {
  return price + (price * rate) / 100;
}
console.log(priceWithTax(1000));
console.log(priceWithTax(1000, 5));

Output:

1130
1050

A function that decides

function grade(marks) {
  if (marks >= 80) return "Distinction";
  if (marks >= 60) return "First division";
  if (marks >= 40) return "Pass";
  return "Fail";
}
console.log([91, 64, 45, 20].map(grade));

Output:

[ 'Distinction', 'First division', 'Pass', 'Fail' ]

A good function does one clear job and has a clear name. If you are copying and pasting the same lines, that is a sign to make a function.

Try it yourself

  1. Write isEven(n) that returns true or false.
  2. Write average(numbers) for an array of numbers.
  3. Rewrite double as a normal function using the function keyword.

Next lesson: JavaScript in a web page.

Finished this lesson?Log in to save your progress and pick up where you left off.
Next lesson →

Comments

Loading comments…

MeroSir Team
A free MeroSir course. Run the examples yourself and try the exercises: you learn programming by doing. Spotted a mistake? Use the Report button above the lesson.
Lesson 6: Functions | MeroSir