w3resource

JavaScript: Function

Introduction

In programming, a function is a section of a program that performs a distinct service. In this sense, a function is a type of procedure or routine. There is some difference between procedure and function in some programming languages where the function returns a value and a procedure perform some operations but does not return a value. In most of the programming and scripting languages, there are some in-built functions that are kept in a library. Besides that you can write your own function, (also called 'User Defined Function' or 'UDF'.) to perform specialized tasks.

Contents:

JavaScript function

Like other programming and scripting languages, functions are one of the fundamental building blocks in JavaScript. Functions are used repetitively in a program and it saves time while developing a web page. To use a function, you must define it somewhere in the scope from which you wish to call it. Defining your own function in JavaScript is a simple task.

Syntax: JavaScript function

function functionName(argument1,argument2..argumentN)
{
  // block of code in JavaScript
}

A function declaration always begins with the keyword function, followed by

  • The name of the newly created function
  • A list of arguments the function accepts, enclosed in parentheses and separated by commas.
  • Block of JavaScript code enclosed in curly braces, { }, to be executed when the function is called.
  • The opening curly brace ({) indicates the beginning of the function code and the closing curly brace (}) marks the termination of a function.

Declare a JavaScript function

For example, to declare a function that calculates the cube of argument passed to it, you can do it in one of two ways:

Note: In arithmetic and algebra, the cube of a number n is its third power — the result of the number multiplied by itself twice: n3 = n × n × n.

Example - 1:

function cube(n) 
{    
return n*n*n; 
}

Example - 2:

var cube = function(n) 
{    
return n*n*n; 
};

The function "cube" takes one argument, called n. There is only one JavaScript statement in function body which instructs to return the argument (n) of the function after multiply by itself twice. Here the return statement returns the calculated value.

Style Guide: Function declaration

Use function declarations instead of function expressions as function declarations are named, so they're easier to identify in call stacks. Also, the whole body of a function declaration is hoisted, whereas only the reference of a function expression is hoisted.

// bad
const foo = function () {
};

// good
function foo() {
}

Never declare a function in a non-function block (if, while, etc). Assign the function to a variable instead.
ECMA-262 defines a block as a list of statements. A function declaration is not a statement.

// bad
if (currentUser) {
  function test() {
    console.log('Nope.');
  }
}

// good
let test;
if (currentUser) {
  test = () => {
    console.log('Yup.');
  };
}

Calling JavaScript functions

We have already learned how to define a function. Defining a function simply names the function and specifies what to do when the function is called.

Calling the function actually executes the instructions written within the function with the indicated parameters.

The arguments of a function are not limited to strings and numbers, you can pass whole objects to a function.

For example, a function called abc() could call as follows.

abc();

In either case, of previous Example-1 and Example-2 you call the function with a line of code similar to the following:

cube(2);

Example - 1:

The scope of a function is the function in which it is declared, or the entire program if it is declared at the top level. You can declare a function below the call and it will work only when you declare the function in function funcName(){} format. The following function will work :

alert(cube(2));
cube = function (n) 
{    
return n*n*n; 
};

The code below will not work.

alert(cube(2));
var cube = function(n) 
{   
return n*n*n;
};

Function scope

The origin from where a function can be accessed is called the function scope. When you defined variables inside a function, they are defined only in the scope of the function, therefore you can not access those variables outside the function. A function defined in the global scope can access all variables defined in the global scope. A function defined inside another function can also access all variables defined in it's parent function and any other variable to which the parent function can access. See the following example:

// The following variables are defined in the global scope
var x = 12, y = 25;

// This function is defined in the global scope
function add(){
  return (x + y);
}

add(); // Returns 37

In the above example x, y and add() are declared in global scope. Therefore add() function can access the values of x and y and return the value of (x+y).

// The following variables are defined in the global scope
var x = 12, y = 25;

// This function is defined in the global scope
function add(){
  return (x + y);
}

add(); // Returns 37

In the second example there is a function called calculation() and add() function is nested inside calculation(). Therefore add() can access all variables defined in it's parent function and return the value of (x+y).

Looking at Parameters Again

There are two types of parameters which are passed to the function, primitive data type parameters and nonprimitive data type parameters. Primitive data types are predefined types of data, for example, integer, character, and string are all primitive data types. Non-primitive data types are created by the user. They are sometimes called "reference variables," or "object references," since they reference a memory location, which stores the data. For example user-defined objects, arrays are non-primitive data types.

If you pass a primitive parameter to a function by value and if the function changes the value of the parameter, the changes are not reflected globally or in the calling function. See the following example:

JS Primitive Parameters

If you pass an object as a nonprimitive parameter and the function changes the object's properties, the changes is reflected globally i.e. it is visible outside the function. See the following example:

function student(theObject)
{
   theObject.name = "Sara";
}

var student1= {name: "Scott", standard: "V", roll_no: 1};
var x,y;
x = student1.name;     // x gets the value "Scott"
student(student1);
y = student1.name;     // y gets the value "Sara"
// (the name property was changed by the function)

If you assign a new object to the parameter, there will be no effect outside the function, because this is changing the value of the parameter rather than the value of individual object's properties. See the following example :

function student(theObject)
{
  theObject = {name: "Sara", standard: "VI", roll_no: 1};
}

var student1= {name: "Scott", standard: "V", roll_no: 1};
var x, y;

x = student1.name;  // x gets the value "Scott"
student(student1);
y = student1.name;  // y still gets the value "Scott"

In the first case, the object student1 was passed to the functions student. The function changed it's name property and it was visible globally. In the second case the function did not change any property of the object, instead, it created a new local variable and have the same name as the global object passed in, so there is no effect on the global object that was passed in.

Style Guide: Function parameters

Never name a parameter arguments. This will take precedence over the arguments object that is given to every function scope.

// bad
function nope(name, options, arguments) {
  // ...stuff...
}

// good
function yup(name, options, args) {
  // ...stuff...
}

Always put default parameters last:

// bad
function handleThings(opts = {}, name) {
  // ...
}

// good
function handleThings(name, opts = {}) {
  // ...
}

Never use the Function constructor to create a new function. Creating a function in this way evaluates a string similarly to eval(), which opens vulnerabilities.

// bad
function handleThings(opts = {}, name) {
  // ...
}

// good
function handleThings(name, opts = {}) {
  // ...
}

Spacing in a function signature:

// bad
const f = function(){};
const g = function (){};
const h = function() {};

// good
const x = function () {};
const y = function a() {};

Closures

Closures are one of the important features of JavaScript. JavaScript allows nesting of functions i.e. you can declare a function inside another function. JavaScript grants the inner function full access to all the variables and functions defined inside the outer function and other variables and functions to which the outer function can access. But the outer function can not access to the variables and functions defined inside the inner function which provides a sort of security for the variables of the inner function. A closure is created when the inner function is somehow made available to any scope outside the outer function. Here is an example:

JavaScript Closure Example -1

Using the arguments object

Using the arguments object, you can call a function with more arguments and it is useful if you don't know in advance how many arguments will be passed to the function. The individual arguments contained in the arguments object can be accessed in the same way array elements are accessed. You can access each argument in the following way :

arguments[i]

where i indicates the position or order of the argument, starting at zero. Therefore the argument passed to a function would be arguments[0], arguments[1], arguments[2]... and so on. The length property of the arguments object contains the number of arguments passed to the function and the total number of arguments is indicated by arguments. length.

The following example illustrates the use of the arguments property. Pass any number of numeric values as arguments, the function will add all those numbers and return the result.:

JavaScript arguments Example

JavaScript: Recursive function

A JavaScript function can even be recursive, that is the function can call itself. The following web document accept a number and computes factorials :

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>JavaScript: Recursive function.</title>
<script type="text/javascript">
function factorial(n)
{
if ((n==0) || (n==1))
return 1;
else 
facn = (n * factorial(n-1))
return facn;
}
</script>
</head>
<body>
<h1 style="color: red">JavaScript Recursive function example</h1>
<hr />
<script type="text/javascript">
function factcal()
{
n=document.form1.text1.value;
result = factorial(n);
alert(" Factorial of "+n+" = "+result);
}
</script>
<form name="form1" action="#">
Input a number :
<input type="text" name="text1" size="5" />
<br />
<input type="button" value="Result" onclick="factcal()" />
</form>
</body>
</html>

View the example in the browser

Complete Example: Find the cube of a number

The following web document accepts a number from the user and it is passed to function cube() by value and return the cube of the number. Within the function we check (through the regular expression) whether the input value is numeric or not, if it is numeric then it will calculate the cube of the number and display through alert() otherwise it will display an error message.

HTML Code

<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Cube of a Number</title>
<link rel='stylesheet' href='form-style.css' type='text/css' />
</head>
<body onload='document.form1.text1.focus()'>
<div class="mail">
<h2>Input a number and get it's Cube</h2>
<form name="form1" action="#">
<ul>
<li><input type='text' name='text1'/></li>
<li>&nbsp;</li>
<li><input type="submit" name="submit" value="Submit" onclick="cube(document.form1.text1)" /></li>
<li>&nbsp;</li>
</ul>
</form>
</div>
<script src="cube-number.js"></script>
</body>
</html>

CSS Code

li {list-style-type: none;
font-size: 16pt;
}
.mail {
margin: auto;
padding-top: 10px;
padding-bottom: 10px;
width: 400px;
background : #D8F1F8;
border: 1px soild silver;
}
.mail h2 {
margin-left: 38px;
}
input {
font-size: 20pt;
}
input:focus, textarea:focus{
background-color: lightyellow;
}
input submit {
font-size: 12pt;
}
.rq {
color: #FF0000;
font-size: 10pt;
}

JavaScript Code

function cube(inputtxt)
    {
      var numbers = /^[-+]?[0-9]+$/;  
	  var x;
	  if(inputtxt.value.match(numbers))
      {
      alert('Cube of '+inputtxt.value+' is '+inputtxt.value*inputtxt.value*inputtxt.value);
      document.form1.text1.focus();
      return true;
      }
      else
      {
      alert('Please input numeric characters only');
      document.form1.text1.focus();
      return false;
      }
    } 
	

View the example in the browser

Previous: JavaScript: const Statement
Next: JavaScript: eval() function



Become a Patron!

Follow us on Facebook and Twitter for latest update.

It will be nice if you may share this link in any developer community or anywhere else, from where other developers may find this content. Thanks.

https://www.w3resource.com/javascript/functions/javascript-function.php