Ad

JavaScript Function Expressions

Function expressions is an another way to declare a function. It allow us to create a new function, similar to an expression.

Function Declaration:

function welcome(){
    alert("Welcome");
}

Function Expression:

let welcome = function(){ //no function name
    alert("Welcome");
}; //semicolon to terminate

Function Declaration: call

welcome(); //will work
function welcome(){
    alert("Welcome");
}

Function Expression: call

welcome(); //error
let welcome = function() { //no function name
    alert("Welcome");
}; //semicolon to terminate

Function Declaration inside scope

"use strict";
let age = 15

if (age < 18) {
    function welcome() {
        alert("Not eligible for vote!");
    }
} else {
    function welcome() {
        alert("Eligible for vote");
    }
}
welcome(); // Error: welcome is not defined

Function Expression inside scope

"use strict";
let age = 15
let welcome;
if (age < 18) {
    welcome = function() {
        alert("Not eligible for vote");
    };
} else {
    welcome = function() {
        alert("Eligible for vote");
    };
}
welcome(); // will work

Function Expression simplify way:

let age = 15
let welcome = (age < 18) ?
  function() { alert("Not eligible for vote"); } :
  function() { alert("Eligible for vote"); };
welcome(); // will work

Function copy

We can copy a function name to another variable. If we write 'alert(welcome)' instead of welcome(), without brackets after welcome, then it will display whole function inside of function call.

Functions are the values that can be assigned, copied or declared in any place of the code.

Function Declaration:

function welcome(){
    alert("Welcome");
}
let greet = welcome;
welcome();
greet(); //will work

Function Expression:

let welcome = function(){ //no function name
    alert("Welcome");
};
let greet = welcome;
welcome();
greet(); //will work

Callback functions

In call back function we pass a function name as an arguments and expect it to be called back later if required.

Example: Callback functions

function someAction(power, sum){
    if(confirm("Want to calculate power"))
        power(); //if yes, call calPower
    else
        sum(); // if no, call calSum
}
function calPower(){
    let a=10;
    let b=3;
    let c=a**b;
    alert('Power ='+c);
}
function calSum(){
    let a=10;
    let b=20;
    let c=a+b;
    alert('Sum ='+c);
}
someAction(calPower, calSum);

Function Expressions with Parameters

We can create parameterized function expression same way as we did in function.

Function Declaration:

function sum(a, b) {
    return (a + b);
}

Function Expression:

let sum = function(a, b) {
  return (a + b);
};

JavaScript Feedback, Questions, Suggestions, Discussion.

Ad: