Javascript Functions: A complete guide for everyone.

Javascript  Functions: A complete guide for everyone.

Overview

what are Functions?

A JavaScript function is a block of code used to Instruct the Javascript engine to do something or execute a particular Instruction, it could be to Add, Subtract, Delete,Print etc.

To further simplify what a function is, think of it as a "Verb"; the same way we use verbs to instruct Humans or even our pets to Go somewhere, Sit, stand etc. We can also Instruct our computer to execute some task, not with verbs like "go,come,add etc" but with a special computer syntax called a "FUNCTION". It is Important to note that Javascript is part of a class of Javascript data types known as Reference Data types

Fundamental features of Javascript Functions

  • A Javascript Function takes an Input: A Javascript Function requires a Parameter (an input) which is a set of values it should work with. A javascript function can take more than one input

  • A Javascript Function returns a value: A Javscript Function should return a value after it has been executed, it could be a result of a mathematical operation or even a Console log of a data


Defining a Javascript Function

When we create a function in javascript it is termed "defining a function" while executing a function is termed "Calling a Function". There are severals ways to define functions in ES7, In this section we will be looking at each one along with when and how to use them.

  1. Function Declaration

  2. Function Expression

  3. Arrow Function

  • Function Declaration

    This is the traditional way functions are defined in all mordern programming languages. It involves the use of the "Function" keyword.

function myFunction(paramA,paramB){
//sets of instruction
}

in the above statement, from L-R we have;

  1. The Function keyword

  2. The name of our function

  3. A parenthesis containing all the parameters(inputs) required by the function

  4. Curly braces within which we have the Instructions we want to feed to the computer

We'll be exploring more realistic examples later in this article, after we must have learnt all there is to functions.

  • Function Expression

    This is a way of defining a function that is more unique to javascript than the function declaration method. It function expression functions are created like variables i.e with the Let, Const or Var keyword

    This way of creating Fuctions is majorly used when we need to store the value returned by our function in a variable for later use, for example when we want to store the result of our mahematical operation into a variable, instead of creating the function with Function Declartion and then storing it in a variable, with function expression we can do all that in one go, isn't this awesome!

//with const keyword
const myFunction= function(paramA,paramB)=>{
//set of Instructions
}

//with Let keyword
let myFunction= function(paramA,paramB)=>{
//set of Instructions
}

//with var Keyword
var myFunction= function(paramA,paramB)=>{
//set of INstructions
}
  • Arrow Function

    This is a mordern javascript way of creating functions, it is preferably used to create functions that does not necessarily need to be referenced later, it is an hybrid between Function Declaration and Function Expression and the most flexible way to create function. For example if we need to create a function we want to execute immediately this is the best way to go about it in Javascript.

    The Arrow function is particularly very useful in software development where we'd need to pass functions into EventListeners as such functions do not necessarily need to be refrenced at a later point.

let myFuction=()=>{
//set of Instruction
}
//Notice the omission of the "function" keyword?

Executing a Javascript Function

Executing a function in javascript is also referred to as "calling a function", it is relatively simpler than defining a function-discussed in the previous section- Calling a function only involves typing the name of the function and adding a parenthesis in front of it, the parentheses often contains values called "Arguments". An example of function of function declaration and execution is given in the code block below.

//declaring the function "addCalc"
function addCalc(a,b){
 console.log(a+b)
}
//executing the function "addCalc"
addCalc(1,3)
//output:4

Arguments vs Parameters:

Whilst most developers often use these terms loosely,there is a subtle difference between them. Parameters are the "values" passed in the parentheses while we are defining a function, they are used within the function to execute several task.Arguments on the other hand are the values we pass into the parenthesis when we call a function. An example is given in the code block below.

function divideCalc(x,y){
//Parameters "X" and "Y" were passed while defining the function divideCalc
console.log(x/y)
}

divideCalc(9,3)
//arguments "9" and "3" were passed whiile calling the function divideCalc

Return Statement

While it may just be sufficent that our function performes a particular task like: addition, deletion,iteration etc; We may sometimes be required to get the result of these tasks and do something with them in our program. In Javascript we can achieve this using the Return statement. The Return statement is defined by using the "return" keyword at the end of our function followed by whatever data we want to return. An example is given in the code block below.

function addCalc(a,b,c){
 return a+b+c
}
let result=addCalc(2,3,1)
//calling the function addCalc and storing the return value of the function in the variable "result"

console.log (result)
//output:6

Function Hoisting in Javascript

Hoisting is a concept most programmers new to javascript often find it difficult to comprehend. The Javascript engine hoist functions and variables by allowing us to use them in our program before they are declared, weird right?

In this section we'll be diving into what hoisting means and how JavaScript functions are hoisted behind the scenes.

Behind the scenes the javascript engine moves all the functions created using the Function declaration syntax, to the top of the script during execution. Because of this(Hoisting) we can call a function in our program even before we create the function. It is important to not that this feature is only available for functions created using Function Declaration. An example is given in the code block below.

//calling the function addCalc
addCalc(4,5)

//declaring the function addCalc after it has been called
function addCalc(x,y){
console.log (x+y)
}

//output:9

to learn more about Hoisting, read this "Hoisting in Javascript"

  • SCOPING

    Scope is the factor that determines the accessibility of variables and functions in our program. There are three major types of scopes in Javascript,viz:

    (1)Block scope

    (2)Function scope

    (3)Global scope

    In this article we'll only be diving deep into the Function scope, to learn more about the rest, check this out

  • Function scope

    Every function created in javscript is an enclosure, variables created inside it are not accessible outside of the functions i.e they can not ne accessed from outside the function. Although functions typically have access to all variables declared in the Global scope, this is often a useful tool to keep in mind while trying to name/access variables them in our program to avoid running into bugs. An example of this is depicted in the code block below

//A function created using the arrow function syn
const myFunction=()=>{
  let name="Moyosore"
  return
}
console.log (name)
//output:reference_Error

Classes of Function

In javascript, function are broadly classified into two based on how they affect the global scope and their side effects. They are;

  • Pure Function

  • Impure Function

PURE FUNCTIONS

These are javscript functions that do always return the same result if the same arguments are passed into it. These functions do not depend on the global scope and are therefore not affected by changes to it. They also do not access do not mutate or alter data outside their scope.

//Example of a pure function
const pureFunction=(greeting)=>{
  console.log(greeting)
}
pureFunction("Hello there")

//output:"Hello World

IMPURE FUNCTIONS

These are functions that produces different result for the same input(argument) passed into it. It contains one or more side effects and mutates data outside it's scope. In standard programming practice, it is often necessary to avoid Impure functions as they produce unpredictable results and often lead to complex bugs.

function randomGenerator(factor){
return Math.random()*factor
}
console.log(randomGenerator(3))

//the output of this code block is unpredictable as it produces different result for similar imput

Comparing Functions and Methods

While Functions and Methods are use loosely, they are quite different. All methods are functions but not all functions are methods. A function defined inside of a Class or Object is referred to as a method. A method can only be executed with refrence to the Class in which it is contained, which an independent function can be executed anywhere in the program without any refrence.

let myObject={
  title:"This is a method",
  data:"Kindly like my articles",
  showObject: function(){
  console.log("Data is here")
  }
}
//The Object "myObject" above contains a method "showObject" which can only be called with refrence to the object i.e myObject.showObject() logs "Data is here" to the console

A Dive Into CallBack Functions

In Javascript a callback function is a function that is passed into another function as an "Argument". Using the callBack function we can write programs where we chain functions to each other so they can call themselves in the order we have defined-like a Domino's effect-.

It is often necessary to require a function run only after the other as been executed, the easiest way to do this in javascript is to use callBack functions.

//defining the function oddOrEven and passing the parameters "number" and "callback" into it
 function oddOrEven(number,callback){
    const result= (number % 2==0)? "Even" : "Odd";
    callback(number, result);
}

//calling the function oddOrEven and defining it's callback
 oddOrEven(24,(number, result)=>{console.log(number + "is" + result)});
//output: 24 is even

In the code block above we used a CallBack function as an argument in our main function to console log the result in our main function. Note that the CallBack funtion will only run after the main function has been called and executed. For more on CallBack functions and how to use them, read this article.


Summary

In this article, we have been able to cover several concepts relating to functions, from how to create simple functions to more complex use cases like CallBacks. As a Javascript programmer, It is Important to know and understand fully how Javascript functions work as the core of most programmes is based on several functions that have been string together.

Do well to go through this article thoroughly and don't forget to like and drop a comment. I wish you a hitch free coding experience; until next time,goodbye!