1.5 - User-Defined Functions

Review

  • We can output to the console with console.log()

  • We can use variables to hold, manipulate, and output data

  • We can do all sorts of maths like Math.round(x) and parseInt(string)

  • We can also work with Strings: my_name.toUpperCase()

  • We can direct traffic (logic) using the conditional if-statement



All that in a few Lessons!

Today's Lesson:

Code is run line-by-line from top-to-bottom. But what if we want to run certain blocks of code whenever we want?

The human body has countless functions from respiratory and coronary, to balance, movement, and sleep. Even just blinking is a function of the human body.

In math and code, functions are very similar - something that happens the same way, every time, whenever we need it.

Examples: Area of a circle, the pythagorean theorem, the quadratic formula...


When you print to the console using console.log(), you are telling the console to do a function - the action (or function) of printing.

JavaScript has thousands of built-in functions, and we will learn several.

let age = prompt("How old are you?"); // The prompt() function

age = Number(age); // The Number() function ( or parseInt() )

console.log("You are " + age + " years old."); // The log() function


We can make our own functions! In programming, these are called "user-defined functions".

  • What if you wanted a function that outputs the current time to the console?

  • How about a function that calculates the area of a triangle?

  • Perhaps a random number generator?

Syntax:

function name() {

// Code goes here

}

Example:

function sayHello() {

console.log("Hello!");

}

To "run" our function, we "call" it:

sayHello(); // This will print "Hello!" to the console


Your Task:

You will be creating a few "user-defined functions" that are all explained in the Replit for this lesson.