Categories
JavaScript

Functions in JavaScript – function objects expressions

Functions in JavaScript

Before stating anything new, I assume you have some idea on functions used in programming languages. Here I have shown how JavaScript is different from traditional function usage in c c++ Java. The traditional use of functions used here in statement form.

A JavaScript function can also be defined using an expression. A function expression can be stored in a variable. The function is actually an anonymous function (a function without a name). Functions stored in variables, do not need function names. They are always invoked (called) using the variable name.



function expression / literal pattern

var functionExpr = function(){
                              alert('hi');
                             };

// call the function expression
 functionExpr();


// Call with parameters
var functionExpr2 = function(a, b){return a * b};
var z = functionExpr2(4, 3);
console.log(z));

Function object creation

var objNew = new Function(‘num1’,’num2’,’return num1*num2’);
 console.log(objNew(3,5)); // Logs 15

Function() constructor takes an indefinite number of parameters, but the last parameter is a string containing the statements constructing the function .
Also you can pass all arguments to be used inside a function as a single comma separated sting as below.

var objNew2 = new Function(‘n1,n2,n3’,’return n1*n2’);
console.log(objNew2(3,5)); // Logs 15

function : Statement Form

function f() {
               alert(“Hello World”);
             }
//Call the function
f();
// This is the simplest for to call JavaScript functions

This is the simplest form of function usage and you have probably used this type of use in various other programming languages.
Save

Save

Save

Save

Save

Save

Save

Save