JavaScript Functions Example Tutorial

JavaScript Functions; In this tutorial, i am going to show you what is JavaScript functions and how to use this functions with the help of examples.

JavaScript Functions

  • Definition Of JavaScript Function
  • How to Declare functions
  • How to Call Function In JavaScript
  • Function hoisting in JavaScript

Definition Of JavaScript Function

A function is a block of code which will be executed only if it is called. Functions are very important and useful in any programming language as they make the code reusable.

When you write a program, you often need to perform the same task in many places. i.e., you want to show a message to the users when they complete an operation.

To avoid writing the same code all over places, you can use a function to wrap that code and reuse it.

JavaScript offers many built-in functions such as alert() and console.log(). Here, you will learn how to create and call custom functions.

How to Declare functions

Use the function keyword, followed by the function name, a list of parameters, and the function body as follows:

function functionName(parameters) {
    // function body
    // ...
}

The function name must be a valid JavaScript identifier. By convention, the function name should start with a verb like getData()fetchContents(), or isValid().

A function can accept zero, one, or multiple parameters. If there are multiple parameters, you need to separate them by commas (,).

The following declares a function named sayHello() that accepts no parameter:

function sayHello() {
   //...
}

The following declares a function named square() that accepts one parameter:

funnction square(a) {
    //...
}

And the following declares a function named sum() that accepts two parameters:

function sum(a, b) {
   // ...
}

Inside the function body, you can implement the logic. For example, the following say() function simply shows a message in the console:

function say(message) {
    console.log(message);
}

In the body of the say() function, we call the console.log() function to show a message in the console.

How to Call Function In JavaScript

Use its name followed by the function arguments enclosed in parentheses, like this:

functionName(arguments);

When you call a function, the function executes the code inside its body. This process is also known as invocation. In other words, you call a function or invoke a function to execute it.

For example, the following shows how to call the say() function:

say('Hello');

The 'Hello' string is an argument that we pass into the say() function.

Parameters vs. Arguments

The terms parameters and arguments are often used interchangeably. However, they are essentially different.

The parameters are used when declaring the function. For example, in the say() function, the message is the parameter.

On the other hand, the arguments are values the function receives from each parameter at the time the function is called. In the case of the say() function, the 'Hello' string is the argument.

Returning a value

Every function is JavaScript returns undefined, unless otherwise specified. See the following example:

function say(message) {
    console.log(message);
}
let result = say('Hello');
console.log('Result:', result);

Output:

Hello
Result: undefined

To specify a return value for a function, you use the the return statement followed by an expression or a value, like this:

return expression;

For example, the following sum() function returns the sum of the two arguments:

function sum(a, b) {
    return a + b;
}

The following show how to invoke the sum() function:

let sum = sum(10, 20);
console.log('Sum:', sum);

Output:

Sum: 30

The following example shows how to use multiple return statements in the function to return different values based on conditions:

function compare(a, b) {
    if (a > b) {
        return -1;
    } else if (a < b) {
        return 1;
    }
    return 0;
}

The compare() function compares two values. It returns:

  • -1 if the first argument is greater than the second one.
  • 1 if the first argument is less than the second one.
  • 0 if  the first argument equals the second one.

The function immediately stops executing when the return statement is reached. Therefore, you can use the return statement without a value to exit the function prematurely, like this:

function say(message) {
    // show nothing if the message is empty
    if (message.length == 0) {
        return;
    }
    console.log(message);
}

In this example, if the message is blank, the say() function will show nothing.

The function can return a single value. If you want to return multiple values from a function, you need to pack these values in an array or an object.

The arguments object

Inside the body of a function, you can access an object called arguments that represents the named arguments of the function.

The arguments object behaves like an array though it is not an instance of the Array type.

For example, you can use the square bracket [] to access the arguments: arguments[0] returns the first argument, arguments[1] returns the second one, and so on. Furthermore, you can use the length property of the arguments object to determine the number of arguments.

The following example implements a generic add() function that calculates the sum of any number of arguments.

function add() {
    let sum = 0;
    for (let i = 0; i < arguments.length; i++) {
        sum += arguments[i];
    }
    return sum;
}

Hence, you can pass any number of arguments to the add() function, like this:

console.log(add(1, 2)); // 3
console.log(add(1, 2, 3, 4, 5)); // 15

Function hoisting

In JavaScript, it is possible to use a function before it is declared. See the following example:

showMe(); // an hoisting example
function showMe(){
    console.log('an hoisting example');
}

This feature is called hoisting.

The function hoisting is a mechanism that the JavaScript engine physically moves the function declarations to the top of the code before executing it.

The following shows the version of the code before the JavaScript engine executes it:

function showMe(){
    console.log('an hoisting example');
}
showMe(); // an hoisting example

Conclusion

In this tutorial you have learned the following:

  • Use the function keyword to declare a function.
  • Use the functionName() to call or invoke a function to execute it.
  • A function implicitly returns undefined, use the return statement to explicitly specify the return value for the function.
  • The arguments is an object that is accessible only inside the function body. It represents the arguments of the function.
  • The function hoisting allows you to place the call to the function before the function declaration.

More JavaScript Tutorials

Recommended:-JavaScript Arrays

Leave a Comment