JavaScript Functions

The JavaScript function is a block of code, which is used to perform a specific task and to create reusable code. These are defined once and maybe executed numerous times. In JavaScript, functions are defined with the function keyword.

There are 3 ways to create a function.

  1. by declaration.
  2. by a function expression.
  3. by the constructor. (good for creating function at run-time.)

Define function by declaration

The most common and practical way is by function declaration.

function msg (status) { 

 	return "Hi" + status;

console.log(msg("users")); // Hi users

Define function by expression

You can create a function without a name. You can assign a function to a variable.

var msg = function (status) { 

 	return "Hi" + status;

console.log(msg("users")); // Hi users

What’s the difference between function declaration and function expression?

Function declaration will hoist the function name and definition to the top, but the function expression assigned to the variable will only hoist the name, not the definition.

f(); // works. returns 3
function f () { return 3; }

g(); // TypeError: undefined is not a function
var g = function () { return 3; }

Function optional parameters

JavaScript doesn’t check the number of arguments passed. If there are more, they are ignored. If less, then extra parameters have values of undefined.

function f (x) { return x; }

// Extra arguments are ignored
console.log(f(2,3,4)); // 2

// Unfilled parameters have a value of 「undefined」
function gg (x, y) { return y; }
console.log(gg(3)) // Prints undefined

Optional parameter with default value

To define default values for an optional parameter, you can just check if an argument is undefined and then set the value.

// Define function with optional parameter and default value

function f (x, y) {

    if ( y === undefined ) {
        y = 3; // Default value

    return x + y;

console.log(f(2)); // 5

About the Author: Pankaj Bisht