💾 Functions

Lesson

💾 Functions

Functions let us use the same piece of code over and over.

They’re a set of instructions which we only have to declare once, and can use many times just by calling the name of the function.

Why are they useful?

It’s better to use functions instead of copying and pasting the same bit of code over and over again. It makes our code way more organised.

How do I use them?

We first need to define the function.

Here’s a simple function that multiplies two numbers:

function functionMultiply(a,b){
  alert('These two numbers multiplied =', a * b);
}

First we let the computer know that we’re declaring a function.

Then we give it a name. This name can be anything, but it’s useful to have something which tells us about what the function does.

Then we need to put brackets (). These can have parameters inside them, such as (a,b) which we can replace with numbers when we call the function. If we use parameters, then we need to include them in the body of the function.

Then we use a curly brackets { } to hold the actual code of what we want to function to do. It’s important to put the closing bracket } right at the end because the function is only listening to what is inside of those brackets!

To actually use the function, we need to call on it.

functionMultiply(3,5);

//These two numbers multiplied = 15

To call the function, we just need to state its name, include values called arguments for any parameters, and finish the line with a semicolon (;).

The code inside the function will then run, in this case printing the result to the console.

We can change the arguments and call the function again to get a different result:

functionMultiply(123,456);

//These two numbers multiplied = 56088

Try It Out

@

Not recently active