2.3 - Functions

Review

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

  • We can do all sorts of maths!

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


All that in 2 Lessons!

Today's Lesson: 2.3 - Functions

Code is run line-by-line from top-to-bottom. But what if we want to run paragraphs of code (called blocks) 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 have the same idea - something that happens the same way, whenever it is asked to.

Example: The Quadratic Formula


When you print to the console using console.log(), you are telling the console to complete a function. The action of printing.

JavaScript has thousands of built-in functions, and we will learn several. A cool one is the prompt() function that allows us to ask the user to give input:

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

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

(Try it)


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?

You wouldn't want to copy and paste that code over and over.

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


Task 2.3

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