JavaScript Functions

Functions are the fun part of JavaScript!

What are functions? They are pieces of code that perform actions. Without functions, JavaScript wouldn’t really do anything.

If you’ve been following along with me in previous posts, you already know some functions! For example, these are functions:

alert()
prompt()

Note: The () next to the function names mean to execute (also called ‘run’ or ‘call’) the function.


When using functions, we can either use existing JavaScript functions, or create our own functions.

How to create a function

1) Function Declaration

Declare/create the function:

function sayHello() {
    console.log("Hello");
}

Call the function:

sayHello();

2) Function Expression

Assign a function to the sayBye variable:

var sayBye = function() {
    console.log("Bye");
}

Use variable to call the function:

sayBye();

Note: When using this, the function itself doesn’t actually have a name. The function has simply been assigned to a variable (sayBye). This is called using an Anonymous Function.


Rather than using an anonymous function, we could have done this instead:

var sayBye = function byebye() {
console.log("Bye");
}

This would have created a function called ‘byebye’.


Examples of declaring and calling functions

Declare the function:

function sing() {
console.log("AHHHHHHH");
console.log("TEEEEEEE");
}

Call the function:

sing();

In this case, if I wanted to later change the song being sung by this function, I’d have to manually type it in and change the function. That would be tiresome.


A better way to do it

Declare the function:

function sing(song) {
console.log(song);
}

Now, any time I want to change the song, I can type:
Input:

sing("I'm just a girl");
sing("I'd rather not be");
sing("Cuz they won't let me drive late at night");

Output:

I'm just a girl
I'd rather not be
Cuz they won't let me drive late at night

Another example

Declare the function:

function multiply(a, b) {
return a * b;
}

Input:

multiply(5, 10);

Output:

50

Note: ‘Return’ is how we get the function to give us something, rather than just log the result in the console. Once you return in a function, the function stops running.


Using IF statements in functions

Declare the function:

function multiply(a, b) {
if (a > 10 || b > 10) {
return "that's too hard";
} else {
return a * b;
}
}

Input:

multiply(5, 10);

Output:

"that's too hard"

Congrats, you’ve made it through learning functions. The best way to become competent with functions is to keep playing with them. Functions may be the hardest part of JavaScript, but they are also where the fun is! Make sure you get a good understanding of functions before moving on to the next topic.

No comments