Functions in JavaScript

Functions in javascript are useful to execute a particular task. To use functions, firstly they have to be defined and then you have to call them to execute. Functions make code reusable. Therefore, they are very important and useful in programming languages. If you want to execute certain code repeatedly, you can create a function with that code and call that function whenever you want.

A javascript function is created with the keyword function, followed by a name and then followed by parentheses (). Function names can be created with letters, digits, underscores, and dollar signs only.
Inside curly brackets i.e {} you can place the code that you want to get executed after calling a function.

Syntax:

function functionName() {
  // block of code to be executed
}

Example:

function simpleFunction() {
  document.write("This is an example of a simple function in javascript.");
}
console.log(simpleFunction());

Output:

The following message will get printed on the webpage.

This is an example of a simple function in javascript.

Functions with parameters:

You can pass parameters to the function inside the parentheses. Multiple parameters are separated by commas.

Syntax:

function functionName(parameter1, parameter2) {
  // block of code to be executed
}

Example:

function addition(a, b) {
  var sum;
  sum = a+ b;
  document.write("Sum of " + a + " and " + b + " is " + sum + ".");
}
addition(23, 22);

Output:

The following message will get printed on the webpage.

Sum of 23 and 22 is 45.

Function Return Value:

You can also return values using functions. In function, use the keyword return and then the value you want to be returned.
The functions in javascript will stop executing when it executes the return statement.

Example:

var sum = addition(5, 8);
document.write("The sum is " + sum);
function addition(a, b) {
  return a + b;
}

Output:

The following message will get printed on the webpage.

The sum is 13.

Function scope:

The variables defined in a function cannot be accessed from anywhere outside the function, because the variable is defined only in the scope of the function. But, a function can access all variables and functions which are defined inside the scope in which it is defined. Meaning, a function defined in the global scope can access all variables defined in the global scope.

Example:

// following variables are defined in global scope
var val1 = 15, val2 = 5;

// following function is defined in global scope
function multiplication() {
  return val1 * val2;
}
document.write("Multiplication is: ", multiplication());

Output:

The following message will get printed on the webpage.

Multiplication is: 75

Additional Links:

Loops in JavaScript

String methods and properties

Arrays in JavaScript

Objects in JavaScript

Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments