Nadeem's blog

JavaScript Functions

work in progress, last updated: May 14, 2020

Introduction

Functions are the main “building blocks” of a program. They allow the code to be called many times without repetition. I would say they are also the most entertaing part of writing a code! Some functions are built-in functions, like alert(message) and prompt(message) but we can create our own functions as well.

Function Declaration

To create a function we need to declare it like this

        
        function showMessage() {
        alert( 'Hello Coders!' );
      }
        
      

The function keyword goes first, then goes the name of the function. We naming a function, use the lowerCamelCase. Then we write a list of parameters between the parentheses separated by a comma,and finally the code of the function, between curly brackets.

        
          function nameOfMyFunction(parameter1, parameter2) {
            the code goes here;
          }
        
      

To call the function we use its name nameOfMyFunction(argument1, argument2). we also provide arguments that we want the function to use. In the example below, we call the function twice, without the need to write the code twice.

        
          nameOfMyFunction(argument1, argument2);
          nameOfMyFunction(argumentA, argumentB);