JavaScript Tutorial - JavaScript Functions

Posted by Ridwan Fadilah on Sep 24, 2020 - 01:04 pm

JavaScript Functions

JavaScript Functions. Learning and understanding of JavaScript Functions. The best part of JavaScript!

“Functions are the very best part of JavaScript. It's where most of the power and the beauty of this language is.” - Douglas Crockford.

JavaScript functions are a subprogram or subroutine that can run in other sections of the program. Functions can perform similar actions in many places of the script.

In other programming languages, we know a method, class, constructor, and module. With JavaScript, we can do these just using JavaScript functions.

This tutorial will attempt to explain the functions available in JavaScript.

Table of Contents

JavaScript Function Syntax

JavaScript function defined with the function keyword, followed by the function name, and also followed by the parentheses ().

The parentheses may include parameter names separated by commas: (parameter1, parameter2, ...).

Here's the syntaxis of the JavaScript function:


function name(parameter1, parameter2, parameter3) {
  // code to be executed
}
The code placed inside the curly bracket is the code that will be executed by the function.

Why Functions?

The reason of why we should use function is because:

  • Reusability (DRY: Do not Repeat Yourself). It means we no need to rewrite the code of a program. With function, we only need to use one block of a program that can use repeatedly.
  • Decomposition / Abstraction. It means to hide the complexity of the program that we write.
  • Modularity. When we hide the complexity with change the program to subprogram or modules, that can help us to find an error.

The 'function' divided into two categories. Built-in function and User-defined function.

A built-in function is a function has made by javascript like:

  • alert()
  • confirm()
  • prompt()
  • etc.

JavaScript Function Invocation

The code of the function will execute when their invokes (calls) by something like:

  • When a user clicks a button
  • When it is invoked (called) from JavaScript code, with or without a conditional statement)
  • Automatically (self invoked)

JavaScript Function Return

JavaScript has a so-called "return" statement. When JavaScript reaches a return statement, the function will stop executing the code.

If the function was invoked from a statement, JavaScript will "return" to execute the code after the invoking statement.

Function often use to compute and return value. The return value is "returned" back to the "caller":


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Function Return Example</h2>

  <p>10 * 3 = </p>

  <p id="demo"></p>

  <script>
    let total = myFunction(10, 3); // Function is called, return value will end up in x
    document.getElementById("demo").innerHTML = total;

    function myFunction(a, b) {
      return a * b; // Function returns the product of a and b
    }
  </script>

</body>
</html>

The example above will display by the browser like this:

See the Pen JavaScript Function Return Example by Ridwan (@ridwan-the-bold) on CodePen.


JavaScript Built-in Function

We are all known that JavaScript has its built-in function. As explained before, a built-in function is a function has made by JavaScript.

This part will attempt to explain two built-in function types in JavaScript that are related to string and math.

Built-in Function - String

There are so many built-in functions in JavaScript that related to string, like: charAt(), slice(), split(), toString(), toLowerCase(), toUpperCase(), etc.

Example:


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Built-in Function--string Example</h2>

  <button onclick="myFunction()">Click Me!</button>

  <p id="demo"></p>

  <script>
    function myFunction() {
      const str = "hello world!",
            res = str.toUpperCase();
  
      document.getElementById("demo").innerHTML = res;
    }
  </script>

</body>
</html>

The example above will display by the browser like this:

See the Pen JavaScript Built-in Function--string Example by Ridwan (@ridwan-the-bold) on CodePen.


Built-in Function - Math

The built-in function in JavaScript that related to math is: sin(), cos(), tan(), random(), round(), floor(), ceil(), log(), etc.

Example:


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Built-in Function--Math Example</h2>

  <p>If you click the button, JavaScript will produce random numbers from 0 - 1 (zero to one):</p>

  <button onclick="myFunction()">Click Me!</button>

  <p id="demo"></p>

  <script>
    function myFunction() {
      let num = Math.random();
  
    document.getElementById("demo").innerHTML = num;
    }
  </script>

</body>
</html>

The example above will display by the browser like this:

See the Pen JavaScript Built-in Function--Math Example by Ridwan (@ridwan-the-bold) on CodePen.


JavaScript User-defined Function

A user-defined function is different from the JavaScript built-in function.

A user-defined function is a function created by the user. Before you learn it, there are some points you need to know about this function:

  • The function must contain the "function" keyword
  • We can add a name of the function (optional)
  • In this function, we can add a parameter/argument
  • Function body place at { }. The body contains a set statement
  • The function can return a value or not

There are two ways to create a user-defined function in JavaScript. The first is using a function declaration, and the second is using function expression.

Function Declaration

Before you learn about this function, you need to know the structure of the function declaration:

Function Declaration Structure

Each JavaScript functions can have a parameter, more than one parameter, or empty.

If the function parameter goes two or more, each parameter should be separated by commas. See the example below:


function myFunction(a, b) {
  // do something
}

Here's the function declaration example:


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Function Declaration Example</h2>

  <p id="demo"></p>

  <script>
    function compute(a, b) {
      let total;
      total = a + b;
  
      return total;
    }

    document.getElementById("demo").innerHTML = compute(5, 6);
  </script>

</body>
</html>

The function above will return the total of 5 + 6:

See the Pen JavaScript Function Declaration Example by Ridwan (@ridwan-the-bold) on CodePen.


The call document.getElementById("demo").innerHTML = compute(5, 6); executes the code of the function.

You can call the function repeatedly:


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Function Declaration Example 2</h2>

  <p id="demo"></p>
  <p id="demo2"></p>

  <button onclick="alert(compute(7, 10))">Click Me!</button>

  <script>
    function compute(a, b) {
      let total;
      total = a + b;
  
      return total;
    }

    document.getElementById("demo").innerHTML = compute(5, 6);
    document.getElementById("demo2").innerHTML = compute(8, 6);
  </script>

</body>
</html>

The function above will return the total:

See the Pen JavaScript Function Declaration Example 2 by Ridwan (@ridwan-the-bold) on CodePen.


Function Expression

The difference between function declaration and function expression is, function expression placed in a variable.

Example:


<!DOCTYPE html>
<html>
<body>

  <h2>JavaScript Function Expression Example</h2>

  <p id="demo"></p>
  <p id="demo2"></p>

  <button onclick="alert(compute(7, 10))">Click Me!</button>

  <script>
    let compute = function (a, b) {
      var total;
      total = a + b;
  
      return total;
    }

    document.getElementById("demo").innerHTML = compute(5, 6);
    document.getElementById("demo2").innerHTML = compute(8, 6);
  </script>

</body>
</html>

In this example, the function name changed to a variable name.

The function above will return the total:

See the Pen JavaScript Function Expression Example by Ridwan (@ridwan-the-bold) on CodePen.


Okay, that's the tutorial about JavaScript Functions. You should know, that's just the basics! You'll learn more about JavaScript in the next chapter.

You can read another JavaScript basics tutorial in the related article below. You can also find another tutorial on our YouTube Channel.

Thanks for reading.


Related Articles