Javascript function


A function is a block of statements, which is used to perform a specific task.In javascript functions are defined with the function keyword.

There are 3 ways to create a function.
1. by declaration.
2. by function expression.
3. by 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 function expression assigned to 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 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 optional parameter, you can just check if a argument is undefined, then set 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

You May Also Like

About the Author: admin