Lesson 7 - Functions in JavaScript

JavaScript Basics Functions in JavaScript

In the previous lesson, Arrays in JavaScript, we learned how to use arrays. Today's JavaScript tutorial is going to be about a very important topic which is functions. Thanks to functions, we'll be able to react to various events in the following lessons such as clicking a button and we're going to program a real web application using this knowledge soon.

Declaring functions

First, let's explain what a function is. It's a block of code which we write once and we can call it multiple times without having to write it again and repeat ourselves. We declare a function using the function keyword, it's block of code is enclosed in braces. A function which will print "Hello, welcome here!" to the document would look as following:

function greet() {
        document.write("Hello, welcome here!");
}

Now we have to call that function. We can only do this after we declare it, otherwise the browser wouldn't know it:

function greet() {
        document.write("Hello, welcome here!");
}

greet(); // calling the function

The result:

Functions in JavaScript
localhost

Functions with parameters

A function can also have any number of input parameters, which we write in parentheses in its definition and we influence the function's behavior by them. Let's consider a situation where we want to greet the visitor using their name. So let's extend our function by a name parameter and pass a concrete value through it when calling the function:

function greet(name) {
        document.write("Hello, welcome here " + name + "!<br />");
}

greet("Carl"); // calling the function

If we needed to greet multiple people now, we won't have to write document.write("Hello, welcome... over and over again like slaves, all we'd have to do is to call our function multiple times:

greet("Carl");
greet("David");
greet("Maria");

The result:

Function parameters in JavaScript
localhost

The function's return value

A function can also return a value. In our example, we don't have to print the text to the document directly (consider we might want to work with the text later so it's not very wise to print it right away from within the function). We can use the return command:

function greet(name) {
        return "Hello, welcome here " + name + "!";
}

let text = greet("Carl");
document.write(text);

Remember the previous example where we printed the names of the week. You can try to rewrite the example so it'd call a function. According to best design practices, all your code should be divided into functions (or into objects, see the following courses) to keep it readable. We omitted this at the start to keep things simple, now please note this :)

As we've already said, the advantage of using functions is readability and space saving (we can code something once and call it a hundred times from different places of the script). If we decide to change a function, we make a change in just one place and this change then affects all the code using the function. This greatly reduces the risk of errors. If we change the text in the function in the example where we're greeting Carl, David, and Maria, all 3 texts would be affected. If we didn't have the code in a function, we'd have to change 3 sentences and we could make a mistake is some of them.

Storing functions into variables

Let's move forward. JavaScript differs from other programming languages in a way it handles functions. Functions are capable of even more things than we've shown so far. Remember how we were talking about the functional paradigm in the introductory lesson? It's a specific programming style which is based upon using functions. We can store a function into an ordinary variable and call it from that variable later.

function greet(name) {
        return "Hello, welcome here " + name + "!";
}

let variable_with_function = greet; // stores the function into a variable
let text = variable_with_function("Carl"); // calls the function from the variable
document.write(text);

In fact, all JavaScript functions are internally variables.

Anynymous functions

A function can be defined directly in the assignment to the variable, we call such a function an anonymous function:

let variable_with_function = function(name) {
        return "Hello, welcome here " + name + "!";
}

let text = variable_with_function("Carl");
document.write(text);

Maybe you wonder whether it's possible to pass a variable containing a function to another function by parameter. Yes, it is! And that's exactly where we were heading. Such functions being passed as parameters of other functions are called callbacks and the whole JavaScript's event model is based upon them. We'll try it on a simple example:

let variable_with_function = function(name) {
        document.write("Hello, welcome here " + name + "!");
}

function call_function(func, name) {
        document.write("I'm a function and I'm calling the function which was passed through my first parameter. <br />");
        document.write("I'm passing a name to it which was passed through my second parameter. <br />");
        func(name);
}

call_function(variable_with_function, "Carl");

The result:

Callbacks in JavaScript
localhost

We've created a function to call another function. It takes the function to be called and the name to be passed to it as parameters. If we wanted to greet in a different way now, we could create another variable with a different function, e.g. variable_with_function2, and pass this variable to the call_function() function instead of the previous variable. Especially in jQuery (see next courses) we'll pass functions like this to events and the functions will be called when the events occur.

If we want to provide multiple input parameters to a function, we separate them with commas. When calling a function, we can even omit some parameters and JavaScript won't treat is as an error, the undefined value will be stored into these parameters instead.

function f(a, b) {
        document.write("a=" + a);
        document.write("b=" + b);
}

f(5);
f(1, 2);

If we want to set a default value for a parameter when it's not provided, we just check whether it's value is undefined and set the default value in this case. As you can see, using functions gives us huge possibilities in JavaScript. In the next lesson, Introduction to DOM and events in JavaScript, we'll see how to handle events using functions and we'll finally create a more interactive application.


 

Download

Downloaded 2x (2.51 kB)
Application includes source codes in language JavaScript

 

 

Article has been written for you by David Capka
Avatar
Do you like this article?
1 votes
The author is a programmer, who likes web technologies and being the lead/chief article writer at ICT.social. He shares his knowledge with the community and is always looking to improve. He believes that anyone can do what they set their mind to.
Unicorn College The author learned IT at the Unicorn College - a prestigious college providing education on IT and economics.
Thumbnail
Previous article
Arrays in JavaScript
Thumbnail
All articles in this section
JavaScript basic constructs
Activities (4)

 

 

Comments

To maintain the quality of discussion, we only allow registered members to comment. Sign in. If you're new, Sign up, it's free.

No one has commented yet - be the first!