A beginner's guide to functions in JavaScript.

A beginner's guide to functions in JavaScript.

Cover photo by IIONA VIRGIN from unsplash.

Functions are pieces of code that perform actions, functions are step by step instructions to perform a particular task in JS. Also, note that functions can perform one action or multiple actions and that depends on how you declare

Contents:

Examples of common functions in JS

  • Prompt()
  • Alert()
  • console.log()

The alert function displays information while the prompt function takes in a value.

Difference between parameters and arguments.

  • Parameters are the values placed in the parenthesis of a function when declaring/initializing it.
  • Arguments are what’s given to a function i.e. what you have in the parenthesis when the function is being called.

**NB: The amount of parameters available in a function determines the number of arguments that function can take on invocation.

An argument can have any type of data. It could be a string, boolean, object, array. etc.**

You can have multiple arguments in a function, and you also can create your own functions and there are two ways by which you can achieve that. See them below.

Ways of creating functions

  1. FUNCTION DECLARATION: also known as NAMED FUNCTION. A function declaration is
    function greeting() {
     console.log(“Welcome Here”);
    }
    greeting();
    

Note that greeting() is a function we created on our own and after the declaration, you have to call it to display whatever we assigned it to, and looking at it console.log(“Welcome here”) is what we're returning from the function.

Let’s reference this to...

const name = "Hannah";

You can’t execute this until you call the variable your string is assigned to which is name

  1. FUNCTION EXPRESSION, also known as anonymous functions
 const goodBye  = function() {
    console.log(“Bye Lharna”);
 }

goodBye();

Here, we assigned the function to the variable, goodBye. so technically the function doesn’t have a name which makes it an anonymous function

I’d like to create a function that consists of fruit juices with different flavors

  function fruit() {
     console.log(“Mango”)
     console.log(“Apple”)
     console.log(“beetroot”)
  }
  fruit();

Imagine having to display different flavors 😳 Stressful right?? Here’s a very simple approach to avoid repetition of codes and make your code efficient. So we make use of parameters and arguments in this scenario to make our functions more extensible, we could do something like...

 function fruit(flavor) {
    console.log(flavor);
 }

 fruit(“mango”);
 fruit(“beetroot”);
 fruit(“pineapple”);

Quite easy and short right? Exactly that’s why we need arguments in our functions to make it easy to edit.

Thank you for reading this article, if it has rekindled your knowledge of the fundamentals of functions in javascript, kindly share it amongst your peers!