function expressions

11 0 0
                                        

syntax for regular function:

function name(){ // statement }

syntax for function expressions:

let name = function(){ // statement };

The difference between the two syntax is the name was use as a variable name and an anonymous function was created after the assignment operator that works the same as the above regular function. And take note of the semi colon at the end of the function expressions since function expressions is just like creating a variable but the value was a function.

================

let globalVariable = function(){

     return "to Earth";

};

function connectingWorld(){

     return 'From Mars ${globalVariable()}';

}

================

HTML

document.write(connectingWorld())

Result:

From Mars to Earth

Note: When we use the globalVariable inside the regular function, we added a parenthesis. The added parenthesis means what we want is the value of the function and not the function itself. So, if we did added the parenthesis, the result would be like this:

From Mars to function(){ return "to Earth"; }

Invoking a function without a parenthesis is useful when you want to copy the function to another variable. And then that  another variable will become another door to your function.

================

let minor = function(){

    document.write("You are minor! You are not allowed to drive.");

};

let adult = function(){

    document.write("You are of legal age. License please.");

};

let question = "Are you an adult?";

function simpleQuestion(ask, f1, f2){

    if(confirm(ask)){

        f1();

    }else {

        f2();

    }

}

================

HTML

simpleQuestion(question, adult, minor)

Result:

You are of legal age. License please.

Note: 

1. In your HTML, i remove the document.write(). I just put the name of the function and all its arguments. So, if you click ok on the pop up menu, result above would show up. If cancel, the function expression minor will run.

2. It depends on the usage, whether you will use a regular function or a function expression.

Javascript ProgrammingWhere stories live. Discover now