This post is work-in-progress learning-note and still in active development and updated regularly.
A JS function is defined as reusable block of codes that are defined at one time and used later repeatedly whenever they are needed. This process avoids writing the same code repeatedly in different part of the program and code repetition. JS functions are the building blocks of the program.
There are some common built-in functions, like alert( message )
, write(message)
, prompt( ),
and confirm(question)
. Often developers write their own custom reusable block of codes as functions to be called later or whenever needed.
In this post, basic concept of function declaration, function expression & arrow function are discussed. Difference been function declaration and function expression are discussed separately in another post.
Function Declaration
JS function declaration (also known as function statement, function definition) is defined using function
keyword followed by name and parentheses ()
.
- The name after parentheses
( )
may contain one or more parameter names (separated by commas:,
). - The block of codes to be executed are placed after the parentheses inside curly braces:
{ }
- Naming rules for function name are similar to naming variables (eg. letters, digits, underscores, and dollar signs).
- For multiple words camelCase pattern is followed.
- Semicolons (
;
) after code blocks{ }
not required like conditional loop syntax construct.
1.Basic Syntax
//Initialize function
function name() { //no parameters
code block to be executed
}
//invoke the function
name(); // no arguments
//FUNCTION WITH PARAMETERS
//Initialize the function
function name(parameter1, parameter2) {
code block to be executed
}
//invoke the function using parameters
name(arg1, arg2);
In the example above, the function is declared with function
keyword followed by name of the function name
. In this simple function, there are no parameters and arguments.
// Initialize function
function helloWorld() { // (1) function declaration
console.log("Hello, World!");// (2) output message
}
// Invoke function
helloWorld(); // (3)
//OUTPUT
Hello, World
In the above example, a simple function helloWorld is declared (1) without any parameter. In the body of the function, a string of welcome of message is logged out (2) in the window console (this is what this function does). When the function helloWorld() is invoked, it outputs the message from (2).
It is important to note that ( )
after function is important to get expected output value, otherwise it outputs function string as shown below.
//function invocation with ()
helloWorld; // note no ()
//OUTPUT in chrome
ƒ helloWorld() {
console.log("Hello, World!");
}
2. Function with Parameters
Lets define a function (below) named userName
with two parameters:
// Initialize function
function userName(firstname, lastname) {
console.log('User fistname is ' + firstname);
console.log('User lastname is ' + lastname);
}
// Invoke function
userName('Mike', 'Smith');
//OUTPUT
User fistname is Mike
User lastname is Smith
In JS function, we often encounter terms parameters and arguments are being used interchangeably. But there is subtle difference between these two terms. When we define or declare a function – the function name ()
parentheses may contain empty (no parameters) or parameters separated by comma which act as local variables. In the above example, the userName
function has two parameters firstname
and lastname
.
Functions arguments on the hand, are values the parameters receive when a function is is called (or invoked). In the above example, Mike
and Smith
are arguments passed the calling function userName()
.
3. Function Invocation
By defining a function does not return a value, it simply names the function with blocks of codes for action when it is invoked. The function invocation is also called execution, calling, or applying it. A function is invoked using function name followed by: ( )
The codes inside the code block (eg. inside curly braces: { }
) is invoked or executed by JS code or self-invoking functions (eg. IIFE), automatically.
//initialize function
function userName(name) {
console.log( name );
}
//invoke (call) function
userName('Dave');
//OUTPUT
Dave
In this example a userName
function is defined to with a single parameter variable name
. When the function userName
was invoked with an argument pass on value of 'Dave'
as username('Dave');
the function was executed and its value was printed in the browser console.
4. Invoking of Function with Parameters
When a function with parameters is invoked, arguments values corresponding to the defined function parameters are passed (or copied) to the function parameters (also called local variables). Then the function executes based on those passed on values.
Function parameters and function arguments are different. Parameters are variables listed in the function definition, whereas arguments are values passed to the function during function invocation.
// Initialize of function
function multiply(a, b, c)
{ return a * b * c; }
// Invoke function with missing argument
multiply(5, 3);
//Output
NaN
// Invoke function extra argument
multiply(5, 3, 4, 5);
//Output
60 //it ignores the extra argument
Function Arguments Rules:
- Missing or unequal arguments in function call does not throw an error
- Function with missing argument (or less than define) return : undefined
- Function call with no-argument – returns : NaN
- Function call with extra arguments than the defined parameters will be ignored.
5. Function Return
The <strong>return</strong>
statement ends function execution and specifies a value to be returned to the function caller.
- A value can be constant, a
var
or any calculation - Value can return by a call of function
- Function has to run to determine its value
- If a value is required in multiple places, assigning a value to a variable is more efficient (eg. function expression).
By using return
keyword, a function can be instructed what value to return. For example:
// Initialize function
function multiply(a, b) {
return a * b;
}
// Invoke function
multiply(5, 3);
//OUTPUT
15
In the example above, return a * b;
code block instructs to multiply the two parameters (a
& b
) and return the value to caller function multiply
. The return keyword also stops execution of function.
In case of function expression, return
keyword assign the value to a variable.
Function Expression
1. Basic Syntax
//Initialize function
var varName = function(param1, param2, .., paramN) {
code block;
}
//Invoke function area
varName(arg1, arg2, .., argN);
Statements involving functions which do not start with function
are function expressions.
// Assign add function to math variable
let math = function add(a, b) { // Named function
return a + b;
}
// Invoke function to find the math value
math(20, 5);
//OUTPUT
25
In the above example, the value of add()
functions were assigned to a new variable named sum
. In this case the sum variable is function. This type of function declaration is called named expression.
We can also rewrite the above example into an Anonymous Function Expression (below) without function name after function
keyword.
// Assign value of the function to math variable
let math = function(a, b) { // anonymous function
return a + b;
}
// Invoke function to find the math value
math(20, 100);
//OUTPUT
120
When functions are stored in variables, as in the above example, the function is invoked using variable name (eg. math). There is no need of function name. However, having named function expression helps in debugging.
Arrow Function
Arrow Functions are similar to anonymous function expression but with shorter syntax and without names (always anonymous). Sometime they are also referred as one line mini functions. Basic explanation of the arrow functions are described below more advanced features are discussed in Arrow Functions on the Mozilla Developer Network.
1. Basic Syntax (MDN)
(param1, param2, …, paramN) => { statements }
(param1, param2, …, paramN) => expression
// equivalent to: => { return expression; }
// Parentheses are optional when there's only one parameter name:
(singleParam) => { statements }
singleParam => { statements }
// with no parameters should be written with a pair of parentheses.
() => { statements }
Using our previous example with two parameters, lets write an arrow function as follows. In arrow function, the initialization is done using =>
(fat arrow) instead of function
keyword. Parameters are passed in small parentheses: ( )
//Initialize the function as anonymous function expression
let add = function (x, y) {
return x + y;
}
//initialize as arrow function
let add = (x, y) => {
return x + y;
}
//Invoke arrow function
add(20, 5);
//OUTPUT
25
2. Arrow Function with one or no parameters
If there is only one parameter, then parentheses are not required.
//Initialize triple function
let triple = x => {
return x * 3;
}
//initialize in a single line as follows
let triple = x => x * 3;
//Invoke function triple
triple(3);
//OUTPUT
9
In case of single line curly brackets { }
and return
keyword could be omitted making the function even shorter.
If there is no parameter, there must have empty parentheses ( )
as shown in the following example.
//Initialize no parameter arrow function
let greeting = () => console.log("Hello, World!");
//invoke our greeting function
greeting();
//OUTPUT
Hello, World!
More advanced features of arrow functions will be discussed in another post.
Resources & Further Reading:
While preparing this post, I have referred the following references extensively. Please to refer original posts for more detailed information.
- 6 ways to declare JavaScript functions – by Dmitri Pavlutin (dmitripavlutin.com)
- Function Expression vs Function Declaration – The Modern JavaScript Tutorial
- Understanding JavaScript Functions – by Zell Liew (zellwk.com/blog)
- Functional JavaScript: Function Composition For Every Day Use – by Joel Thoms (hackernoon.com)