Advanced Javascript Tutorial

Function

Definitions

There are several ways to define function.

//function
function fja1() {}

//function assigned to variable
var fja2 = function() {}


//function assigned to object
var obj = {
    fja3: function() {}
}


console.log(typeof fja1 +': '+fja1);
console.log(typeof fja2 +': '+fja2);
console.log(typeof obj.fja3 +': '+obj.fja3);

 

Example: 01fun_definition.js

 

 

 

Parameters

function (par1, par2) { }

 Parameters can be variables, objects or callback functions.

 

The following code browser support, but NodeJS don't support this parameter definition.

function (p1, p2=5) {

      //...some code

}

Example: 02fun_parameter_var.js

 

Callback as a parameter

//define function with callback
function fja(p1, cb) {
    
    res = p1 +10;
    cb(p1);
}


//define parameters
var x=2;

var cb1 = function(a) {
    console.log(a);
}


//call function
var res = fja(x, cb1); //2

Callback function defined as a variable: 03fun_parameter_callback.js

Callback function: 03fun_parameter_callback2.js

Calback defined as an object: 03fun_parameter_callback3.js

 

 

 

 Scope of global variable

Each global variable is accessible everywhere inside and outside functions. Global variable is defined without var keyword.

And of course global variable is accesible inside callback function.

Variable defined in global scope is accessible inside each function:  05fun_var_in_global_scope.js

Global variable inside one function is accesible inside another function: 05fun_var_in_global_scope.js

Global variable is accesible inside callback function: 07fun_global_var_in_callback.js