JavaScript Functions, a Pocket Reference
Functions are callable objects in JavaScript. It is very important to note that in JavaScript functions are objects. It might be misleading because when you use the typeof
operator on a function, you get function
as the output. This is one of the instances where JavaScript lies to you. The output of typeof function () {}
should be object
because functions are objects in JavaScript. That makes functions very powerful, because you can think of them as callable objects. You can use a function as an object, a piece of reusable code, or a function that creates objects.
Creating Functions
There are two main ways of defining functions:
- function declaration
- function expression
If a statement starts with the function
keyword, then you have a function declaration:
function myFn() {}
But if you assign a function to a variable, you have a function expression:
const fnRef = function myFn() {};
Note that you need a semi-colon when creating a function expression, but you should not include one when creating a function declaration.