Shining  Light on javascript functions.

Photo by Isaac Davis on Unsplash

Shining Light on javascript functions.

A Beginners guide to Vanilla JS (Plain JS) functions

What is a function?

Think of a function as a recipe, where you write steps to cook the best dish. If those steps are followed correctly then you nail the meal. For example, A meal for 5 requires more additional ingridients which means if you prepared a meal for 3 last time, you would use the same recipe but add additional quantities for the ingredients.

Technical Defination:

A function is a block or set of reusable code that is used to perform a given task.

Function Declaration (function defination or function statement)
/* Declare the function 'rectangle' */
function rectangle(length,width) {
  return length* width;
}
  • Function name (optional) In the case where a name is not provided its called an anonymous function

    rectangle

    /* Anonymous function */
    function (length,width) {
    return length * width;
    }
    
  • List of parameters separared by commas (parameters can be variables or objects)These are also optional

    length, width

  • Function body (also optional)

    return length * width;

How are functions created?

a. Function Expressions - A javascript function can also be defined using an expression

const rectangle = function(length, width){
     return length * width);}

b. IIFE (Immediately Invoked Function Expression) - This is a function that runs immediately it's defined.

(function (){
   /*statements*/
})()

c. Conditionally created functions - Functions declared inside an if statement

if (true) {
function a(){
return b;}

d. Hoisted functions - functions called before there declaration

rectangle();
function rectangle(length,width) {
  return length* width;
}

Note: function expressions are not hoisted, only functions

e. Generator function - It is a function that can return multiple values one after another.

function from(start) {
    return function () {
        var next = start;
        start += 1;
        return next;
    };
}
var generate = from(0);
console.log(generate());
console.log(generate());
console.log(generate());
console.log(generate());
/*output*/
0
1
2
3

f. Arrow function (=>) are an alternative to traditional functions apart from:

  • It does not have its own bindings to this or super, and should not be used as methods.
  • Does not have new.target keyword.
  • Not suitable for call, apply and bind methods, which generally rely on establishing a scope. see here
  • Can not be used as constructors.
  • Can not use yieldwithin its body. -Do not have 'arguments object'.
let message = {
  name: "Marty",
  regularFunction: function () {
    console.log(this); /*this refers to the owner of the function that we are excecuting*/
    console.log("Hello " + this.name); /**output: Hello Marty*/
  },
  arrowFunction: () => console.log("Hello " + this.name), /*this refers to the global window therefore 'this.name' returns 'undefined'*/
 /**output: Hello */
};

message.regularFunction(); /*it looks for name in the function object and when it does find find it, it displays it as Marty which is in the function property*/

message.arrowFunction(); /*it looks for name in the window and when it does not find it, it does not display it as name is not part of window property*/

console.log(this); /*Window Object*/

Best useCase for arrow functions is

  • setTimeout
  • setInterval
  • addEventListener

g. Function Constructor - these are functions created with the new operator

function fn (){
this.fname = value;
this.lname = value;
}
/*Now we create the function*/
let person = new fn();

h. Function Prototypes - This is a special object in which additional properties can be attached across all instances of it's constructor function

function Person(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

let john = new Person('John', 'Doe', Person.prototype.age = 15);
console.log(john.firstName); 
console.log(john.lastName);
console.log(john.age);

Conclusion

In this Article, I have tried to exhaust the fundamentals of functions and how they are created. Learn more about functions from MDN Web Docs