JavaScript Functions

JavaScript functions; In this tutorial, you will learn about the JavaScript functions with the help of examples.

JavaScript Functions

A javascript function is a block of code that performs a specific task. Which can be called anywhere in your program.

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

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.

Declaring functions

To declare a function, you 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.

Calling functions

To call a function, you 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.

Recommended JavaScript Tutorials

Recommended:-JavaScript Arrays

AuthorDevendra Dode

Greetings, I'm Devendra Dode, a full-stack developer, entrepreneur, and the proud owner of Tutsmake.com. My passion lies in crafting informative tutorials and offering valuable tips to assist fellow developers on their coding journey. Within my content, I cover a spectrum of technologies, including PHP, Python, JavaScript, jQuery, Laravel, Livewire, CodeIgniter, Node.js, Express.js, Vue.js, Angular.js, React.js, MySQL, MongoDB, REST APIs, Windows, XAMPP, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL, and Bootstrap. Whether you're starting out or looking for advanced examples, I provide step-by-step guides and practical demonstrations to make your learning experience seamless. Let's explore the diverse realms of coding together.

Leave a Reply

Your email address will not be published. Required fields are marked *