JS: function | JavaScript

JavaScript function

JavaScript functions are the sub-routines of a program i.e. reusable piece of code, to wirte repeating functionality once and use as many times as required to avoid re-write the same code.

function name(param1, param2){ //function code here }

function call

function is called with () postfix, i.e. followed by the function name.

alert();  

The above code will show empty box because we just called the function but didn't provide a text to show.

caller and callee functions

function sayHi(){ console.log('Hi!'); } sayHi(); Hi!

In the code above, sayHi is the caller function whereas alert is the callee function.

Why function

  • Easy to maintain an application
  • application is divided into small piece easy to manage
  • Simple bug resolving

Function return

Function may return a value. return statement is optional. if return ommited, function returns undefined. Function execution terminated as the interpreter reaches to return statement. Function returns a value to the statement that called the function.

function pi(){ return 3.142857142857143; } var x = pi(); console.log(x); 3.142857142857143

function returns undefined if return statement ommited.

function test(){ var i = 0; } var x = test(); console.log(x); undefined

Multiple return statements

Function containing muliple return statements, the control is returned when JavaScript interpreter reaches any of the return statement first.

function test(){ if(false) return 0;//will not return as interpreter not reached here due to false condition return 1;//returns to calling statement } var x = test(); console.log(x); 1

The above code returns 1 beacuase if(false) does not move the cursor to return 0. So, return 1 causes to return value to caller statement (var x = test() in the above case).

function unreachable code warning

The function code after return statement is unreachable.

function warn(){ return 0; return 1; } warn(); unreachable code after return statement

The statement return 1; is not reachable because the function warn return 0 which terminates the execution of the function. The above warning is displayed (if display Warnings are enabled in your browser).

Function parameter

Function parameter is a variable to hold the value passed into the callee function from the caller statement/function:

function square(p1){ return p1 * p1; } var x = square(3); console.log(x); 9

p1 is the parameter. The function call square(3) passes 3 to the function for p1.

parameter scope

parameter variables are limited to the function only.

parameter by value

The primitive data types in JavaScript are passed by value. i.e. change in the argument value does not change the value of the passing variable.

function byVal(p1){ p1 = 100; } var x = 5; byVal(x); console.log(x); 5

parameter by reference

The composite data types in JavaScript are passed by value. i.e. change in the parameter value changes at the same memory address.

Object parameter by Reference

Object parameter is passed by reference. Change in passing variable is passes the address of the address of the object.

function byRef(p1){ p1.a = 'changed value'; } var obj = {a:'default value'};//changing the value of property p1.a byRef(obj);//passing obj to byRef console.log(obj.a); changed value

function byRef changes the value of property a. This is because p1 contains the reference (memory address) of the passing object (obj) instead of value. This is the diffrence when we pass a primitive data type variable e.g. number, boolean or string.

Array parameter by Reference

Array parameter is passed by reference just like objects.

function byRef(p1){ p1[0]=90; } var arr = []; arr[0]=3; byRef(arr);//passing arr to byRef console.log(arr); 90

Function arguments ommition

JavaScript does not throw error if number of function arguments passed are less than the parameters in the function definition:

function arg(p1, p2, p3){ //some code here } arg(1);

function arguments addition

JavaScript does not throw error if number of function arguments passed are more than the parameters in the function definition:

function arg(p1, p2, p3){ //some code here } arg(1,2,3,4,5);

Function arguments

arguments keyword provides the arguments (parameter values) passed to the function in order they passed:

function arg(p1, p2, p3){ for(var i=0;i< arguments.length;i++) console.log(arguments[i]); } arg('first','second','third'); first second thrid
argument means parameter value

Parameters default value

JavaScript functions may have default parameter values.

function messageBox(p1 = 'Hello!'){ console.log(p1); } messageBox('Hi!'); //shows the passed value i.e. Hi! messageBox(); //shows the default value i.e. Hello! Hi! Hello!

First we called messageBox passing 'Hi!', the JavaScript interpreter gave priority to the passed argument over default value, that's why displays Hi!. Secondly, we called the same function messageBox with no parameter, so JavaScript interpreter set the default value 'Hello!' to the parameter p1, displaying Hello!

params parameter

The params parameter

Function arguments behaviour

arguments depends on the number of values passed into the function, not the parameter in the definition:

function arg(p1, p2, p3){ for(var i=0;i< arguments.length;i++) alert(arguments[i]); } arg('first','second','third','fourth','fifth'); first second thrid fourth fifth

As we can observe that the function arg in the above code have three parameters p1, p2, and p3 but we passed five arguments 'first', 'second', 'third', 'fourth' and 'fifth'. The arguments provide all the passed arguments. In case no parameter defined in the function definition and we send arguments, all arguments are accessible through the arguments keyword.

Parameter and Argument difference

The variable holding the passed value is the parameter of the function. The value passed to the function is argument.

function messageBox(message){ console.log(message); } messageBox('Hi!'); Hi!

In the code above, message is the parameter whereas 'Hi!' is the argument.

Nested function

JavaScript allows nested functions i.e. function within a function:

function outer(){ function inner(){ //inner function statements here } }

Here, outer is the parent function whereas inner is the nested function.

The nested function is accessible within the parent function only.

Annonymous function

Annonymous functions are declared without an identifer. Annonymous may be assigned to a variable. Annonymous functions are mostly used for a callback function.

var inrement = function(value, by = 1){ return value + by; } var x = inrement(10, 8); console.log(x); 18

Function constructor

JavaScript function can be declared with Function constructor. All arguments are passed as string. The last most arguments is the function body as string. Arguments other than last argument are the parameters of the function. Constructor function is created with new keyword.

var inrement = new Function("value", "by = 1", "return value + by;") var x = inrement(10); console.log(x); 11

JavaScript Function Recursion

function calling itself is called recursion. Function recursion is a programming technique supported by the most programming languages like c#, Java, c++ etc.

function factorial(x){ if(x > 1) return (x * factorial(x-1)); //factorial calling itself return 1; } var x = factorial(5); console.log(x); 120

Arrow function

Arrow function are the new syntax for to declare a function defined in ECMAScript 2015 (ES6). This the syntactical sugar of the classic syntax of the function.

var pi = () => 22/7; var x = pi(); alert(x); 3.142857142857143
  • Simplified, easy to read
  • Arrow function having single expression, return that expression.
  • Arrow function also called Lambda Function

Immediately Invoked Function Expression (IIFE)

Immediately Invoked Function Expression (IIFE), prounounced iffy, runs where it is defined. IIFE used to avoid hoisting. IIFE is used to avoid overwriting global variables/identifiers particularly when different JavaScript files are used in a single application or web page.

(function () { //function variables and code here })();

IIFE consists of two parts, first is declaration.

(function () { //function variables and code here })

and second is calling

()

IIFE may also have arguments.

(function (n1, n2) { var fullName = n1 + " " + n2; alert(fullName); })("Ever","Student"); Ever Student

IIFE is also called Self-Executing Anonymous Function but this is not a standard terminology. The IIFE term was introduced by Ben Alman .

Function hoiting

JavaScript moves the function declaration and the function to the top, this is called Hoisting. Variables declared with var also hoised but not their value. Please look into the Hoisting chapter for details.

isHoisted(); function isHoisted(){ console.log('Yes! hoisted'); } Yes! hoisted

Function Declaration vs Annonymous Function

Named functions are declared with name where as annonymous function have no name but treated as an expression usually assigned to a variable. Named or Decalred functions are parsed and hoisted before execution of the script whereas annonymous functions are not. Annonymous functions are parsed when the JavaScript interpreter executes the related expression.

Take a look at the following codes:

declared(); function declared(){ alert('Parsed and Hoisted'); } Parsed and Hoisted

declared is called before its decalration and it was successful. Since declared is a named function that's why it as hoisted i.e. JavaScript interpreter moved the function definition to the top of the script. This is why the statement declared() is known to the JavaScript interpreter.

annonymous(); var annonymous = function(){ console.log('annonymous function'); } TypeError: annonymous is not a function

annonymous is called before it is defined, so raised error. Since annonymous is assigned an annonymous function that's why it was unknown to JavaScript interpreter moved. This is why the statement annonymous() raised error.

So, call a annonymous function after it was defined and assigned:

var annonymous = function(){ console.log('annonymous function'); } annonymous(); annonymous function

Notes

  1. JavaScript functions are hoisted to top
  2. JavaScript function returns undefined if return ommited
  3. JavaScript function may have unlimited parameters
  4. If JavaScript function redefined, the latest definition will work.
  5. return is optional, function returns undefined if return ommited

Practice Assignments

Following celsius to fahrenheit conversion function named CtoF accept temperature in celsius and return the value in fahrenheit:

function CtoF(c){ var f = c * 9 / 5 + 32; return f; } var c = 37; var f = CtoF(c); console.log(f + ' °F'); 98.6

Farenheit to Celsius in JavaScript

Following fahrenheit to celsius conversion function named FtoC accepts temperature in fahrenheit and return the value in celsius:

Code to program in JavaScript, to convert temperature from Farenheit to Celsius

function FtoC(f){ var c = (f - 32) / (9/5); return c; } var c = FtoC(98.6); console.log(c + ' °C');