Mark As Completed Discussion

In this lesson, we will learn about functions in a program, with a focus on the following key points,

  1. What are functions, and why do we use them?
  2. Working with function parameters, return, and call statements.

For the Python version of this lesson, please click here.

In this lesson, we will learn about a fundamental concept in programming called functions. Functions provide a modular structure to the code. They perform a single action and provide a method to reuse a code block in different parts of the program. Functions are known by various terminologies in computer science. Methods, procedures, and subroutines are some of the common ones.

Functions

A function is a block of code in a programming language that encloses a set of statements. Once implemented, this block of code is reusable throughout the program. Functions make it easier to organize and reuse code.

A function generally follows the following structure in a program.

Functions

Let's discuss each of these components of functions in the next sections.

Types of Functions

In programming languages, there are usually two types of functions; built-in functions and user-defined functions. Built-in functions are pre-defined by the programming language itself. We've already seen built-in functions in previous lessons such as print(). User-defined functions are functions that are defined by the user to dedicate a block of code to perform a specific task.

In this lesson, we will discuss how you can create and use your functions within your program.

Creating Functions

Function declaration or creating functions is different in different programming languages. Usually, a function keyword is specified, followed by the function name, parenthesis (with function parameters, if any), and then comes the body of the function.

Now let's see how we can create functions in JavaScript.

JavaScript functions are declared using the function keyword. This is followed by the function name and parenthesis. The body of the function is denoted using curly braces.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Calling Functions

In our last code example we created a function, but as you may have checked, it did not produce any output. Why? Because functions need to be invoked by a call to use them in a program. Calling a function means to specify the function name of the function that we want to use in the program. This executes all the statements present inside the function.

Consider the same example as in previous section. Now we specify a statement which denotes the function name along with the parenthesis, after the function implementation. This statement invokes the call to the function. The code block below demonstrates this behavior.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Let's test your knowledge. Is this statement true or false?

We can call a function before implementing it.

Press true if you believe the statement is correct, or false otherwise.

Function Parameters

Functions can take in external information in the form of variables or directly through function parameters. They are specified inside the parenthesis after the function name. Multiple parameters can be separated by commas.

Function parameters are given a variable name inside the parenthesis during function declaration. The desired values are passed when the function call is invoked. Below code block demonstrate some examples of specifying function parameters and calling functions with parameters.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Try this exercise. Is this statement true or false?

There is no limit to the number of parameters that we can specify for a function.

Press true if you believe the statement is correct, or false otherwise.

Returning Functions

Functions stop executing at two points; when it finishes executing all statements in the function body or when it encounters a return statement. This return statement mostly also has a return value associated with it, which is returned to the caller.

The function sum(a, b, c) in the following code block implements the sum of three numbers and returns the sum. This sum is then returned to the variable that calls the function, which is named as result here. Printing the value of the variable result tells us the value of the sum computed by the function.

JAVASCRIPT
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment

Build your intuition. Fill in the missing part by typing it in.

What will be printed by the variable result, in the following code block?

JAVASCRIPT
1function div(a, b){
2    c = b/a
3}
4
5var result = div(15, 5)
6console.log(result)

Write the missing line below.

Are you sure you're getting this? Click the correct answer from the options.

What is the printed on the console for the following code?

JAVASCRIPT
1function compare_num(a, b){
2    if (a > b){
3        console.log("a is greater than b")
4        return a
5    }
6    else if (a == b){
7        console.log("a is equal to b")
8        return a
9    }
10    else{
11        console.log("a is less than b")
12        return b
13    }
14}
15
16var result = compare_num(4, 2)
17console.log(result)

Click the option that best answers the question.

  • 'a is greater than b', 2
  • 'a is less than b', 2
  • 'a is greater than b', 4
  • 'a is equal to b', 4

Summary

Functions are an extremely helpful technique to reuse and organize code. With specifying parameters and return statements, we can do more with functions that are just combining a set of statements, and even specify different values from the entirety of the program that we want to work upon. A common beginner's mistake is to forget to call the implemented functions when using them in code. Don't fall for it!

One Pager Cheat Sheet

  • We will learn about functions and their usage in programs, focusing on function parameters, return and call statements.
  • Functions provide a reusable block of code that follows a certain structure, making it easier to organize and reuse code in a program.
  • By using built-in functions or defining user-defined functions, programmers can create code that allows them to easily perform specific tasks in their program.
  • In JavaScript, functions are declared using the function keyword, followed by the function name and parenthesis, with the body of the function denoted using curly braces.
  • We invoked a function by specifying its name and enclosing it with parenthesis, executing all the statements inside it.
  • It is not possible to call a function before it is defined or implemented.
  • Functions can take in external information through function parameters, which are specified inside the parenthesis after the function name and separated by commas.
  • The number of parameters for a function is completely up to the programmer, as they serve as placeholders to pass in values when the function is called.
  • A function can return a value to its caller, as seen in the code block with the sum(a, b, c) function, which is then stored in the result variable and printed to show the calculated sum.
  • The variable result prints undefined, as the function div does not have a return statement and therefore does not return a value.
  • The code prints "a is greater than b" to the console and returns 4 as the result, producing a console output of 'a is greater than b', 4.
  • You can reuse and better organize your code by using functions, however don't forget to call them when using them in your program.