JavaScript Functions

·

4 min read

JavaScript Functions

What are Functions?

Functions in programming languages are a reusable block of codes. They are reusable because they can be called up at different points when writing codes, by simply calling the function name. When creating every function it must have a key word "function" to alert the computer that you are about creating a function, this is followed by a function name, and parameters if needed, followed by statements which would be executed by the function. These statements are usually found inside the function's curly braces. Let's look at an example:

     function functionName(/*parameters are written here if needed */) {
           console.log("Welcome to my Blog!");
     }
     functionName(/* arguments are written here when needed */)

In the example above, the name of the function was functionName, and the function was to log "Welcome to my blog!" to the console. note that after creating a function, we had to call/invoke the function. Please note that when calling a function, they are called with arguments if required. Also note that after the function keyword there is no space between the function name and the parentheses and there is a space between the parentheses and the opening curly brace. If the function name is more than a word it is best to write it using camelCase.

In ES6 the new way of creating a function is:

    const functionName = () =>{
          console.log("Welcome to my Blog!");
    }
    functionName();

Please note the spaces used in the code above and where necessary, also note that the previous way of declaring a function with the keyword function is still valid.

Difference between a Parameter and an Argument

Parameters are variables used that can be defined when declaring a function, they can possess different types while Arguments are values assigned to the declared variables and are used when calling/invoking a function.

Okay let's write another function, that logs my favorite movie.

     function logFavoriteMovie() {
         console.log("Being Mary Jane");
     }
     logFavoriteMovie();

Let's write another function but this time with parameters and arguments. We'd write a function that takes in first name and last name and logs a greeting that greets somebody by first and last name and we'd call the function twice with different names.

     function welcomeNote(fname,lname) {     
           let greeting = "Good Morning";
           console.log(`${greeting} ${fname} ${lname}`);
     }
     welcomeNote("Nmesoma","Ogbonna");
     welcomeNote("John","Williams");

When this code runs it would read "Good Morning Nmesoma Ogbonna" and "Good Morning John Williams"

Function return

When a function carries out an operation it returns a new value when invoked, for example if a function performs a calculation like 8 + 4. It will return the a new value "12". let's see an example:

    function sum(a,b) {
         return console.log(a+b);
    }
    sum(4,2);  // output: 6 //
    sum(5,8); // output: 13 //

In the example above we created a function that takes in two parameters and returns their sum. You can also see that we were able to assign new values to these variables when calling them.

Conditional statements

In javascript the if else statements are used when writing conditionals, they mark a block of statements to be executed depending on a condition. For example we are telling the compiler "if (x===3) then alert "correct!" else alert "wrong answer". Conditionals are written using expressions, operators and statements.

Difference between Expressions and Statements

Now expressions and statements are mostly interchanged so let's define them so we have a better understanding, A statement is a complete line of code that performs some action, while an expression is any valid code that resolves into a value and can be written whenever you would expect a value.

Let’s now look at the basic structure of a conditional;

     if (expression) {
        statement;
     } else {
        statement;
     }

Let's see some examples;

    let screenTime = 12;
    function screenTimeCheck() {
        if (screenTime === 6) {
           console.log("Good Job! You're not addicted to your phone"); 
        } else {
          console.log("Your screen time is high ");
        }

    }
    screenTimeCheck();

Now let's add parameters and arguments,

    function carGame(age) {
         if (age === 18) {
            console.log("Welcome! Please Fasten your seatbelt.");
         } else if (age < 18) {
             console.log("Sorry, you're not allowed to drive.");  
         } else if (age > 18) {
             console.log("Please enjoy your ride.")
         }
    }
    carGame(14);

In the example above we wrote a function for a game that checks that you must be an adult to be able to play the game.

Conclusion

We've been able to learn;

  • how to declare and call a function with or without parameters and arguments,

  • the difference between a parameter and argument as well as expressions and statements.

  • return functions and also conditional statements.

Happy Coding!