Functions are Objects in Java Script

// I found this to be a very interesting concept about functions in Java Script

//Copy this entire text into your text editor or console and run and execute all sections at the same time to understand how a function performs as an object. Also take a look at how I can say “hi” three different ways by using a function, a variable that is a function, and a function parameter that is a function//

//Example 1//

//An Expression is a unit of code that returns a value such as:
 
var a;

a = 3;

a;

console.log(a);    

//Returns the value of the variable "a",  as     a = 3 in first console.log output//

// Example 2//

//A Function Statement does not return a value//

//The function is placed into memory but it does not have a value until it is run.//  

//However, it will be put in memory ahead of time.  I can call greet before I define it.//

greet();   //This will return the first "hi"

function greet() {
 console.log("hi")

};

//This function statement returns the value of "hi" when it is run by calling the function by name.//

// Example 3//

//Now here is a Function Expression where a value is given and stored in memory.  Here the function is defined as a variable and is stored in memory but if called before it is defined it will return undefined

var anonymousGreet = function(){
    console.log("hi");
};

//Now we can call these functions and variables and get the same output.  However the greet function is stored and the var "anonymousGreet" is stored but you cannot call the  anonymousGreet before defining the variable.  Both will return the value "hi"//


anonymousGreet();  //This will return the 2nd "hi" in the console//

//Example 4

//Now lets look at using a function to call a function.  A function within a function//

//Now this is is crazy!! To call the parameter of a function named log and to invoke itself by calling the parameter which is itself a function.  You must call the parameter as a function because it is defined as such.  This opens up a new type of programming called functional programming.  Now all three of the last examples give the same output which is "hi" by using three different approaches to programming.  All four examples will show up in the console.log when you open the browser console. //


function log(a){a();};     //This will return the 3th "hi" in the console

log(function(){console.log(“hi”)})

VM2098:14 3 console.log(a);
VM2098:29 hi greet();
VM2098:39 hi anonymousGreet();
VM2098:57 hi function log(a){a();
undefined

// I hope you find this as fun as I did

1 Like