JavaScript Function Declaration – Parameters, Expression, Types of Functions

In most of the JavaScript tutorials, we heard about functions and its parameters. But, what is JavaScript function, how it can work, what are its parameters etc. we don’t know. So, in this JavaScript function tutorial, we will learn function declaration, parameters, and expression with examples.

Introduction to JavaScript Function

What is JavaScript Function?

A function is a set of statements that take inputs, and performs specific computation and produces output. Basically, a JavaScript function is a set of statements that performs some tasks or do some computation and then returns the result to the user. JavaScript also supports the use of functions. We can create functions in JavaScript using the keyword function.

This is the basic syntax to create a function in JavaScript.

Function functionName( Parameter1, Parameter2…)
{
// function body
}

To create a function in JavaScript, we have to first use the keyword function, separated by name of function and parameters within parentheses.

Do you know how to declare a variable in JavaScript?

JavaScript Function Definition/Declaration

Before using a user-defined function in JavaScript, we use to create one. We can use the syntax to create the function in JavaScript. A function definition is sometimes also termed as declaration or function statements.

The rules for creating the JavaScript function is as follows:

  • There should be unique user-defined names.
  • A list of parameters enclosed within parentheses and repeated by commas.
  • The list of statements composing the body of the function enclosed within curly braces.

Example 

function calcSubtraction(number 1, number 2)
{
Return number 1 – number 2;
}

In the above example, we have created a function named calcSubtraction, this function accepts two numbers as parameters and returns the subtraction of these two numbers.

JavaScript Function Parameters

1. Calling Functions

We can call a function in JavaScript by using the function name separated by the value of parameter enclosed between parentheses and a semicolon at the end.

functionName(value 1, value 2…);

Example

<script type = “text/javascript”>
// function definition
function welcomeMsg(name) {
  documents.write(“Hello” + name + “Welcome to New York”);
}
//creating a variable
Var nameVal = “Admin”;
//calling the function
WelcomeMsg(nameVal);
</script>

Output

Welcome to New York

Let’s revise the – Syntax of JavaScript

2. Return Statement

We can use the return statement in JavaScript. The function is calculating two numbers and then returning the result. The most basic syntax of using the return statement is the return value.

JavaScript Function Expressions

We can create a function expression by assigning a function to a variable.

//Assign add function to sum constant
count sum = function add(xy) {
  return x+y;
}
//Invoke function to find the sum
Sum(10,20);

Output: 30

Now, the sum constant is a function. We can make this expression more concise by turning the autonomous function, which is an unnamed function. Currently, our function has the same add, but with a function expression, it is not necessary to name the function.

Example

//Assign function to sum constant
const sum = function(x,y) {
{
Return x + y;
}
//invoke function to find the sum
sum(200, 4);
}

Output: 204

In this example, we have removed the name of the function that is add function and returned into an anonymous function. A name function expression could be used to help in debugging.

JavaScript Arrow Functions

Arrow functions are always anonymous functions and they are the type of function expression.

Example

//define multiply function
const multiply = ( x , y) => (
  return x * y;
//Invoke function to find product
multiply (20,4);

Output: 80

Instead of writing the keyword function, we use => arrow to indicate a function. Otherwise, it works similarly to a regular function expression, with some advanced differences while you can use about under Arrow Functions on the Mozilla Developer Network.

Example

//define square fuction
const square = x => {
   Return x * x;
}
// invoke function to find product
square(9);

Output: 64

Note: In the case of no parameter an empty set of parentheses() is required in the arrow functions.

Do you know how to construct loops in JavaScript?

With these particular examples that only consist of a return statement, arrow function allow the syntax to be reduced even further. If the function is only a single live return, both the curly braces and the return statement.

//invoke function to first product
  square(20);

Output: 400

A function is a parametric block of code defined one time and called many times. In JavaScript, the function is compared and influenced by many components.

  • JavaScript code that forms the function body.
  • The list of function parameters.
  • The variables were accessible from the outer scope.
  • The returned.
  • Named or anonymous function.
  • Argument object in JavaScript.

JavaScript Regular Function

The function declaration matches for cases when regular functions are to be created. Regular means that you declare the function once and later invoked it in many different places.

Example

function sum (a, b) {
return a + b;
}
sum(10, 20);
([10, 15]).reduce (sum)

Output: 30

25

Contrary to function expression or arrow functions that do not create binding with the function variable by its name.

Example

function factorial(n) {
 If ( n == 0) {
   return 1;
 }
return n * factorial( n- 1);
 }
factorial(5);

Output: 120

JavaScript Function Declaration Vs Function Expression

Function declaration and Function Expression looks very similar. But produce a function with different properties. A function declaration in a statement always starts with the keyword function.

Example

//function declaration : starts with “function”
 function isNull(value) {
  return value == null;
}

In the case of function expression, the JavaScript statement does not start with a function keyword.

Also, See – JavaScript Loop Control

Example

//function Expression : starts with “var”
 var isTruth = function(value) {
   return!! Value;
};
//function Expression : an argument for .filter ()
var number = ([1, false, 5]).filter (function(item))
{
  Return typeof item == ‘number’;
});
//function Expression: starts with “C”
  (function messageFunction(message) {
    Return message + ‘world’;
  (‘Hello’);
})

Function Declaration in Conditional Statement

Some JavaScript environment can throw a reference error when invoking a function whose declaration appears within blocks { …} of it, for or while statement.

(function) () {
‘use strict’ :
if (true) {
function ok() {
  return ‘true ok’ ;
}
}
else {
  function ok() {
    return ‘false ok’;
  }
}
console.log(typeof ok == ‘undefined’); // => true
console.log(ok()); //Throws “Reference Error”: ok is not defined
();
}
})

Named Function Expression

A function is anonymous when it is an empty string ‘ ‘.

Example

var getType = function(variable) {
   return typeof variable;
};
getType. name;

Output: ‘ ‘

getType is an anonymous function and getType.name is when the expression has the name specified, then is a named function expression. It has some additional properties in comparison with simple function expression:

  • Inside the function body variables with the same name holds the object.

Example

var getType = function funName(variable) {
 console.log(typeof funName == ‘function’);
  return type of variable;
}
console.log(getType ();
console.log(getType_name);
console.log(type of funName == ‘function’);

Output: True

Number fun Name false

The variable funName is accessible within function scope, but not outside.

Favor Named Function Expression

While a variable assignment is used with a function expression var fun = function() { }, many engines can infer the function name from this variable. Often callbacks are passed as anonymous functions expressions, without storing into variables: so the engine cannot determine its name.

It seems reasonable to use named function and avoids anonymous ones. This being a series of benefits:

  • The error messages and call stacks more detailed information when using the function names.
  • More comfortable debugging by reducing the number of anonymous stack names.
  • It is possible to access the function name inside its scope for recursive calls or detaching Event Listeners.

Recommended Reading – Best Books to Learn JavaScript

Shorthand Method Definition

You can define Shorthand Method Definition using a function name, followed by a list of parameters in a pair of parentheses (para1, paramN) and a pair of curly braces {…} that delimits the body statement.

Example

var collection = {
 Items: [ ],
  add(…items) {
   this.item.prints( …items);
};
get(Index) {
 return this.items[index];
}
};
collection.add( ‘C’, ‘Java’, ‘PHP’);
collection.get(1);

Output: Java

The short approach of method definition has several benefits over traditional definition with a name, colon: and a function expression add:function(…)

  • Shorthand syntax is easier to read and write.

JavaScript Class syntax requires method declarations.

Example

class star {
constructor(name) {

  this.name = name;
}
getMessage(message) {

   return this.name + message;
}
}
Var sun = new star(‘sun’);
Sun.getMessage(‘is shining’);
}

Output: sun is shining

Computed Property Names and Methods

The computed properties use a slight different syntax[methodName]() { … }, so the method definition looks this way:

var addMethod = ‘add’,
getMethod = ‘get’;
var collection = {
    items: [ ],
[addMethods] (..items);
};
[getMethod] (index) {
   Return this.items[index];
}
};
collection [addMethod] (‘C’, ‘Java’, ‘PHP’);
collection[getMethod](1);
[add Method] (…) {…} and getMethod(…) {….} are shorthand method declarations with computed property names.

Context Transparency

This keyword is one of the most confusing of JavaScript.ECMA Script 6 improves this usage by introducing the arrow functions, which takes the context lexically.
this is inherited from the outer function

Example

class Number {
  constructor(array) {
    this.array = array;
}
addNumber(number) {
  if (number ! == undefined) {
    this.array.push(number);
}
return(number) => {
   console.log(this == = numberObjects);
   this.array.push(number);
};
}
}
Var numberObject = new Numbers([]);
numbersObject.addNumber(1);
var addMethod = numbersObject.addNumber();
addMethod(5);
console.log(numberObject.array);
}

Output: [1, 5]

Number class holds an array of numbers and provides a method addNumber() to insert new numbers.

Have a look – JavaScript Switch Case with Example

When addNumbers() is called without arguments, a closure is returned that allows to insert numbers. This closure is an arrow function, which has this as numbersObject instance, because the context is taken lexically from addNumbers() method.

Without the arrow, function is necessary to manually fix the content. It means adding fixes by using .bind() method.

//
return function(number) {
console.log(this==numberObjects);
this.array.push(number).bind(this);
//…

Example

// …
 var self = this;
  return function (numbers) {
  console.log(self = numberObject);
 self.array.push(number);
};
//…

The context transparency property can be used whenever you want to keep this as is, taken from enclosing context.

Short Callbacks

Let’s use an in-built method to find if an array has 0 elements.

var numbers = [1, 5, 10, 15];
numbers.some(items => item == 0); // => true

JavaScript Generator Function

The JavaScript Generator Function syntax is similar to a function expression, function declaration or method declarations, just that it requires a star character.

a. Function declaration form function * <name>();

Example

function * indexGenerator () {
  var index = 0;
while(true) {
   yield index++;
 }
}
var g = indexGenerator();
console.log(g.next().value);
console.log(g.next().value);

b. Function expression form function * ()

var indexGenerator = function*() {
  var index = 0;
    while (true) {
      yield index ++;
 }
};
var g = indexGenerator();
console.log(g.next().value);
console.log(g.next().value);

c. Shorthand method definition from *<name> ();

var obj = {
        * indexGenerator() {
        var index = 0;
        while (true) {
        yield index ++;
}
}
}
var g = obj.indexGenerator();
console.log(g.next().value);
console.log(g.next().value);

Summary

With the help of function keyword, we can define JavaScript function. A function can include one or more parameters. It is optional to specify functions parameter values while executing it. JavaScript is a loosely typed language. A function parameter can hold the value of any data type. JavaScript allows you to create an anonymous function that must be assigned to a variable. Hope, you liked our explanation. You may also like to know about Latest JavaScript Career Opportunities.

Furthermore, if you have any query, feel free to ask in the comment section.

Leave a Reply

Your email address will not be published. Required fields are marked *

This site is protected by reCAPTCHA and the Google Privacy Policy and Terms of Service apply.