Your browser doesn't support the features required by impress.js, so you are presented with a simplified version of this presentation.

For the best experience please use the latest Chrome, Safari or Firefox browser.


JavaScript Function -
Meet the First Lady.

What is function?

Why do we use it?

A function is a logical piece of job.

You invoke it to get that job done.
In JS, function has below signature:
    
        function functionName(args) {
            //logical piece of job
            ...

            //may or may not return result to the caller
        }

        functionName(); //Function invocation
        
Unnamed function:
    
        function () {

            //something dreamy...
            console.log("Hello, it's me!");

        }

        How do you invoke this sleeping beauty?
Welcome function as

First Lady*

* Let's get a reference to it and pay respect to it.

        var firstLady = function () {
            
            //something dreamy...
            console.log("Hello, it's me!");

        }; //notice this semicolon.


        and can get to it anytime like this:

        firstLady(); //Function invocation using its reference
        

A word of caution on function hoisting

Create function using constructor:

          var functionRef = new Function('a', 'b', " return a + b ");

          console.log("Result is: " + functionRef(1, 3));
        

Function in JS isObject! A First Class Citizen.


Function being an object opens
doors to do the Unthinkable!
Array of functions:

        var chessMoves = [
            function () { console.log("King's move"); }, 
            function () { console.log("Queen's move"); },
            function () { console.log("Bishop's move"); },
            function () { console.log("Pawn's move"); }
        ];
                                             
        chessMoves.forEach(function (move) {
            move();
        });

        Depending on the piece you want to move,
        you can selectively apply the function.
        
Yes, you can apply function!!!
        Function being an object has methods 
        called apply() and call() to invoke it:

        firstLady.apply()

        or

        firstLady.call() 
        
        Difference between the 2 is reader's exercise.
        
Let's apply function:
        var chessMoves = [
            function () { console.log("King's move"); }, 
            function () { console.log("Queen's move"); },
            function () { console.log("Bishop's move"); },
            function () { console.log("Pawn's move"); }
        ];
                                             
        //King's move
        chessMoves[0].apply();
        

You can imagine array of functions as a screw driver with replacable heads.

Depending on screw you want to screw :-), you pick function selectively and apply it.

Function can be passed to other functions.
These are called callback functions.

Run code asynchronously as in event listening or AJAX.
Examples:

        1. Event Listener: $(selector).on(event, function () {
            //React to the event
        });

        2. AJAX: $.ajax({
            url: url,
            type: '',
            ...
            success: function (result) { // Callback when success
                //show results
            },
            error: function () { // Callback when failure
                //report error
            } 
        });
        
A simple callback function in action:

        var displayContent = function (content) {
            console.log('File content: ' + content); //Consumer
        }

        var readFile = function (callback) {
            console.log('Reading a long file...');

            var fileContent = 'This is file content'; //Producer

            callback(fileContent);  //calling Consumer
        }

        readFile(displayContent);
        
Why just pass function?
We can return it as well!
Returning function:

        function getChessMoveFor(piece) {
            switch(piece) {
                case 'King': 
                    return function () { console.log("King's move"); }
                case 'Queen': 
                    return function () { console.log("Queen's move"); }
                case 'Bishop': 
                    return function () { console.log("Bishop's move"); }
                case 'Pawn': 
                    return function () { console.log("Pawn's move"); }
            }
        }

        var move = getChessMoveFor('King');
        move(); //Make King's move
        
arguments object:
        function example() {
          console.log(arguments[0] + arguments[1] + arguments[2]);
        }
         
        example(1, 2, 3);
        
Memoization:

        function square(num){
          var result = '';
          if(!square.cache[num]){ 
             console.log("Computing value...");
             result = num*num;
             square.cache[num] = result;  
          }

          console.log(square.cache[num]);

        }

        square.cache = {}; //Cache property in function object
        
Memoization continued:

          square(10); //Computing

          square(10); //From Cache

          square(20); //Computing

          console.log(square.cache); //key value hash
        
Function as Transformer:

        function transformer(arg) {
            console.log('I am ' + arg + ' Car');

            transformer = function (newArg, moreArg) {
                console.log('I am Robo fighting ', newArg, moreArg);
            }
        }

        transformer('Lamborghini');

        transformer('Bad Robo', 'and Worse Robo');         
        
Immediate Function:

        (function(){
            console.log('Hello, I am an immediate function');
        }());


        (function(){
            console.log('Hello, I am immediate function V2');
        })();
        
Nested Function:

        function startCar(inputKey) {
          var key = chipKey();  //Some onboard chip function

          function startEngine(inputKey) {
            function fireSparkPlug() {
              console.log('Key matched. Car Started. Vroom..vroom');
            }
            if (inputKey == key) {
              fireSparkPlug();
            }
          }
          startEngine(inputKey);
        }

        startCar(12345);
        




It's time for some OOPs!

Thank you!!!

Use a spacebar or arrow keys to navigate