DEV Community

Cover image for Advanced Javascript Functions
John Wanjema for Lux tech Academy

Posted on

Advanced Javascript Functions

What is a Javascript functions

A function is a block of organized,reusable code that is used to perform a single,related action.

Advanced Working with Functions

Function basics include function declarations,passing parameters and function scope.
check out this article that cover into to Javascript functions.
Javascript Functions

In this article we are going to discuss the following:

  • The new function
  • Immediately invoked functions
  • closures
  • Arrow functions
  • This keyword
  • The call method
  • The apply method
  • The bind method
  • Default parameters
  • Rest parameters
  • Spread parameters

The new function

The new operator lets developers create an instance of a user-defined object type or of one of the built-in object types that has a constructor function.

function Car(make, model, year) {
  this.make = make;
  this.model = model;
  this.year = year;
}

const car1 = new Car('VW', 'GTI', 2017);

console.log(car1.make); // VW
Enter fullscreen mode Exit fullscreen mode

Immediately Invoked Function Expression(IIFE)

An IIFE Lets us group our code and have it work in isolation,independent of any other code.
Invokes a function right away where its defined.
This prevents functions and variables from polluting the global object.

(function hello() {
    console.log('Hello World'); //Hello
})();
Enter fullscreen mode Exit fullscreen mode

To make it a function expression, we assign it to a variable or use it in another expression.

closures

A closure is a feature in JavaScript where a function inner scope has access to the outer scope.
In the example below closure help keep message within the scope and it can be accessed in the getMessage function.

let greeting = (function () {
    let message = 'Hello';
    let getMessage = function () {
        return message;
    };
    return {
        getMessage: getMessage
    }
})();

console.log(greeting.message); //Hello
Enter fullscreen mode Exit fullscreen mode

Arrow functions

Arrow functions were introduced ES6.Refers to anonymous functions with their own unique syntax.Simpler way to create a function.

Why?

  • shorter syntax
  • this derives it value from enclosing lexical scope

Shortcomings.

  • Arrow functions don't have their own this value.
  • No argument object - we can't reference arguments
let greet = () => {
    return 'Hello world';
}
let message = greet();
console.log(message); //Hello World
Enter fullscreen mode Exit fullscreen mode

If there is one parameter parenthesis are optional.

let greet = name => 'Hello' + name;
Enter fullscreen mode Exit fullscreen mode

This keyword

Refers to the owner of the function we are executing
So if it's a standard function,this refers to the global window object;otherwise it can refer to the object that a function is a method of.

let message = {
    name: 'john',
    regularFunction(name) {
        console.log('Hello' + this.name)
    },

    arrowFunction: () => console.log('Hi' + this.name)
}

message.regularFunction(); // Hello John
message.arrowFunction();// Hi
Enter fullscreen mode Exit fullscreen mode

The call method

The call() allows for a function/method belonging to one object to be assigned and called for a different object.
call() provides a new value of this to the function/method.
With call(), you can write a method once and then inherit it in another object, without having to rewrite the method for the new object.

let car1 = { brand: 'Vw', color: 'blue' }
let car2 = { brand: 'Toyota', color: 'white' }

let returnCarBrand = function () {
    console.log('Car brand is ' + this.brand)
}

returnCarBrand.call(car1); // Car brand is Vw
returnCarBrand.call(car2); // Car brand is Toyota
Enter fullscreen mode Exit fullscreen mode

The apply method

The apply() method calls a function with a given this value, and arguments provided as an array.
Same syntax as call difference is that call accepts an argument list, while apply accepts a single array of arguments.

function bookTitle(name, author) {
    console.log(name + 'is written by ' + author);
    console.log(this);
}
bookTitle.apply(['HTML & CSS: Design and Build Web Sites', 'Jon Duckett']);
Enter fullscreen mode Exit fullscreen mode

The bind method

Allows to make a copy of a function and then change the value of this.

let book = {
    author: 'Mary',
    getAuthor: function () {
        return this.author;
    }
}

let book2 = { author: 'John' };
let getAuthorcopy = book.getAuthor.bind(book2);
console.log(getAuthorcopy()); // John
Enter fullscreen mode Exit fullscreen mode

Default parameters

Allow named parameters to be initialized with default values if no value or undefined is passed.

function sayHi(message, name = 'John') {
    console.log(message + name)
}
Enter fullscreen mode Exit fullscreen mode

Rest parameters

The rest parameter syntax allows a function to accept an indefinite number of arguments as an array.
Rest parameters should always come after regular parameters.

let sayHi = function greet(...names) {
    names.forEach(name => console.log('Hi ' + name))
}
greet('Welcome', 'John', 'Mary', 'James') // Hi John // Hi Mary // Hi James
Enter fullscreen mode Exit fullscreen mode

Spread Operator

Allows an a function to take an array as an argument and spread out its elements so that they can be assigned to individual parameters

function greet(user1, user2) {
    console.log('Hello' + user1 +' and ' + user2)
}
let names = ['John','Mary']
greet(...names); //Hello John and Mary
Enter fullscreen mode Exit fullscreen mode

Top comments (2)

Collapse
 
sujit510 profile image
Sujit Singh

Good article John.
Just one correction: In "Rest parameters" section code snippet, you have indicated the out put as // Hi John // Hi Mary // Hi James
It would also include // Hi Welcome in the beginning, won't it?

Collapse
 
wanjema profile image
John Wanjema

yes ill correct that