What exactly is a function in JavaScript?

What exactly is a function in JavaScript?

Introduction

It took me six months to fully understand the concept of functions in JavaScript. You read that right.

When I just started coding in javascript, I wrote a lot of shitty code as I was new to the programming world, I had a lot of document.getElementById() and document.querySelector() everywhere in my code, no grouping, no splitting, no reusability, just throwing console.log() and alert() everywhere. As a beginner, this bothered me a lot and made me sought out new ways of writing codes in javascript, after watching some tutorials I got a new idea and a better way to group my codes.

Functions

As a concept in coding, it allows you to store a piece of code that does a single task inside a defined block, and then call that code whenever you need it using a single short command. MDN Web Docs

To get a clearer view of javascript function, let me use a farmer as an illustration; for a farmer to have full control over his cattle he/she build a fence around them to keep them together else the cattle will stray and looking for them is obviously a difficult task.

cow.png

Image source: Alibaba

cow2.jpg

Image source: Farm and Diary

A javascript function is a block of code that performs a specific task when they are called.

for more clearer picture:

  //instead of doing this

   let digits = [1,2,3,4,5,6];
     const sum = digits.map(function(n){
     return n*2
    })
   console.log(sum)

  //output:[2,4,6,8,10,12]

The code above will run correctly but the way it's left out in the open is actually not a good practice, its variable is globally scoped which can later land us in big trouble as the codebase grows. To prevent such thing from happening we can use javascript function to build a block around our code and our variable can be scoped to locally to the function.

 //do this
    function doubleThaNumbers(){
       const digits = [1,2,3,4,5,6];
       const sum = digits.map(function(n){
       return n*2
    })
    console.log(sum)
  }

   //output:[2,4,6,8,10,12]

the code above doubles the number in the array and logs it in the console

Two ways you can create functions in javascript

Function Declaration

function hello() {
// logics here
console.log("Hello World")
}

// output: Hello World

Function Expression

const hello = function () {
// logic here
console.log("Hello World")
}
// output: Hello World

Calling functions

After creating a javascript function, you need to call it before it can run

hello()

This function prints "Hello World" in the browser's console.

Parameters and Arguments

When creating a function, we can pass a placeholder for incoming data that is to be processed in the function, this placeholder is called a parameter, and when calling a function the value that is being passed into the function is called function arguments you can call a function with parameters and pass in an argument as shown below;

function hello (name, age){
    console.log("Hello! My name is " + name+ " and I am "+age+" years old")
}

// calling the function

hello("Dellyson", 21)

//output: "Hello!, my name is Dellyson and I am 21 years old"

What happens if some of the arguments are missing?

When calling the function above, If I pass in only one argument the second argument will automatically be assigned an undefined value.

For example:

hello("Dellyson")

//output: "Hello!, my name is Dellyson and I am undefined years old"

This can be handled by setting a default value for the parameters.

   function hello(name, age="default age"){

       console.log("Hello! My name is " + name+ " and I am "+age+" years old")

   }

// output:"Hello!, my name is Dellyson and I am default age years old"

When writing javascript codes if all you do just like I used to is writing document.getElementById() everywhere without using functions as a fence around your code, someday you will run into some errors that will take you nights to debug.

Javascript function gives some advantages which include:

  • Code reusability.
  • Keeping a bunch of code together in a function block
  • Helps you write an easy to debug code
  • Keeps your codebase organized

Writing reusable code is a life-saving practice, you don't want to have a duplicate of any line of your code everywhere in your codebase.

For example:

// instead of doing this every time

const submitBtn  = document.getElementById("#btn")
const toggleBtn = document.getElementById("#toggleBtn")

The lines of code above have some repetition which is against the DRY (Don't Repeat Yourself) principle. you can create a function that takes an element as a parameter and return the selected element using the return keyword.

Example:

// do this

function getById( element) {
    return document.getElementById(element);
}

In the code above, I basically created a getById() function which takes in a parameter of element, all this function does is to return a selected element return document.getElementById(element), we can now use the function like so;

// use it 
const submitBtn = getById("btn");
const toggleBtn = getById("toggleBtn");

btn.addEventListener("click", function(){
console.log("Hello World!")
})
//output: "Hello World!"

toggleBtn.addEventListener("dblclick", function() {
  console.log("double clicked!!!")
})

//output:"double clicked!!!"

Conclusion

With the help of a javascript function and parameter, I was able to create a basic reusable code that I can call anywhere and anytime I want. See you in my next post. Peace ✌.