It’s no secret that functions in JavaScript are first-class citizens. But what does that actually mean? While the name JavaScript suggest a certain similarity with Java, JavaScript is in essence extremely different. In Java, everything revolves around Classes which instantiate into Objects, while in JavaScript the main building block of your application is a function. Also, in JavaScript, everything is an object… even functions!
This is how we define a function in JavaScript:
1
2
3
function functionName (/* parameters */) {
/* body */
}
While every programmer recognizes this template and might know how functions work, JavaScript allows more than just executing them. For example, you can:
- store them in variables
- define them as properties of an object
- add properties to the function object
In fact, functions in JavaScript are much like objects. They even have native properties and behaviour such as a name property and methods like call or apply.
1
2
var example = function myName () {/* body */};
console.log(example.name); // outputs myName
In JavaScript, functions hold great power by being able to pass them along as values (and parameters).
However, it doesn’t stop there… functions have even more tricks up their sleeves.
Find out in our next blog post of the 5 minute JavaScript.