In this article, we'll go over the definition of functions and why they are so important. I'll also show you how to get started writing functions in JavaScript.
Let's dive in!
What is a function in JavaScript?
The code inside a function runs only when it is needed, meaning only when it is called.
Functions are an important and useful part of programming because they create reusable code. Instead of copying, pasting, and repeating the same code throughout different parts of your program, you can write that code only in one place using a function. Then you can use it over and over again whenever you have to.
Instead of looking for the different parts where your code could be, you only have to look at one particular place which makes your code more readable.
Function declarations
The general syntax for creating a function in JavaScript looks like :
function name (parameter1,parameter2,..){
//block of code
}
name()
Let's break it down:
We declare the function with the keyword
function
. This keyword tells JavaScript that we are trying to define a function.In the next step, you give the name to function as per your convenience. Remember in JavaScript they are case sensitive the best is to use
camelCase
.The function name is followed by a set of opening and closing parentheses.
Parameters vs Arguments
Parameters are variables listed as a part of the function definition.
Arguments are values passed to the function when it is invoked.
An argument is the value of a parameter.
Here a and b are parameters
and values passed (2, 2) are the arguments
.
Parameter without a default value
Parameter is variable msg whereas empty, undefined, and Hey yo are arguments passed into greeting() function.
Hoisting
Consider the code below:
example();
function example(param) {
// ...
}
See what I did there? I called our example
function before even defining it. Surprisingly, the code snippet can be executed without any errors. That's an example of exclusive property of function declaration called hoisting. It's related to the way that JS engines process code - first they analyze function declarations and then everything else.
To learn more about hoisting:JavaScript Hoisting