Free Trial

Safari Books Online is a digital library providing on-demand subscription access to thousands of learning resources.

  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint
Share this Page URL
Help

4. Function() > Functions Are First-Class Citizens (Not Just Syntax but Values)

Functions Are First-Class Citizens (Not Just Syntax but Values)

In JavaScript, functions are objects. This means that a function can be stored in a variable, array, or object. Also, a function can be passed to, and returned from, a function. A function has properties because it is an object. All of these factors make functions first-class citizens in JavaScript.

Live Code

<!DOCTYPE html><html lang="en"><body><script>

/* functions can be stored in variables (funcA), arrays (funcB), 
and objects (funcC) */
var funcA = function(){}; // called like so: funcA()
var funcB = [function(){}]; // called like so: funcB[0]()
var funcC = {method: function(){}}; // too.method() or funcC['method']()

// functions can be sent to, and sent back from, functions
var funcD = function(func){
   return func
};

var runFuncPassedToFuncD = funcD(function(){console.log('Hi');});

runFuncPassedToFuncD();

// functions are objects, which means they can have properties
var funcE = function(){};
funcE.answer = 'yup'; // instance property
console.log(funcE.answer); // logs 'yup'

</script></body></html>

  

You are currently reading a PREVIEW of this book.

                                                                                                                    

Get instant access to over $1 million worth of books and videos.

  

Start a Free Trial


  
  • Safari Books Online
  • Create BookmarkCreate Bookmark
  • Create Note or TagCreate Note or Tag
  • PrintPrint