Different ways of writing a function in JavaScript — Part I
In this post we are going to learn about functions in JavaScript and different ways of writing it.
Anatomy of a function
A simple function in JavaScript can written as follows:
function test() {
console.log(‘hello world’);
}
Here ‘test’ represents the name of the function and the code inside { and } represents the body of the function. A function can be called by its name followed by ( and ). So to call the function above we write test();
Okay enough of the basics, lets dive into different ways a function can be declared in JavaScript and its uses.
‘typeof’ operator and function:
Though function is not a primitive data type, the ‘typeof’ operator returns a string “function” when you ask for its type. So
console.log(typeof test); // prints a string “function”
A quick puzzle for our readers. How do you print the contents of a user defined function in JavaScript? For example, I want to print the function test above along with the code inside it. How can I do it? Keep thinking and reading, I will tell you how
A function can be declared in the following ways in JavaScript
- Function declaration