Call a Function

After a function is defined, you can use it from outside the function by calling it's name followed by the parenthesis with necessary input argument values.

function_name(p1_value, p2_value...)`

Actually we've been using this already. When we need to run the code in a function, we need to do function call. Function call contains the name of the function to be executed followed by a list of values, called arguments, which are assigned to the parameters in the function definition.

Using the specified function name anywhere in your program and any number of times, you can run that block of code.

Call the Function directly to run the code in it

After the function definition, we call the function to run it on a new line.

function sayHi() {
    console.log("Hi!");
}

sayHi();

The last line is not indented because it is out of the function already. We simply type the function name with the empty parenthesis since this function has no input arguments. By clicking the 'run' button, we can see the result is displayed in the console:

Hi!

Call the function in some lines of codes

Let's call sayHi() in a for loop:


for (let t = 1; t < 4; t++) {
    console.log(t);
    sayHi();

Console result:

1
Hi!
2
Hi!
3
Hi!

These few lines of statements use for loop to call the function sayHi() 3 times: at t=1,2,3, each time t is printed out before calling say_hi(), so the console shows the above message.

Call function in another function definition

We can call sayHi() in another function definition, continue with the above lines:

function sayMorning() {
    sayHi();
    console.log("Good morning!");
}

// call the function to run it
sayMorning();

Run and see the console:

Hi!
Good morning!

Here we define another function sayMorning(), in this function there are two lines of statements: call function sayHi() and print another message.

Next we call the function sayMorning() on a new line with no indention, click run, then the codes in the function first execute function sayHi() printing out Hi!, then execute next statement console.log('Good morning!') printing out message Good morning!

Exercise:

Please define a function, sing(), call this function to print out a message: Happy birthday to you!

answer:

function sing() {
    console.log('Happy birthday to you!`);
}

// call function
sing();

results matching ""

    No results matching ""