Javascript Functions

Functions

Functions are the fundamental building block of any programming language. A function is a set of statements that performs a particular task and can be reused again.

A Function is a block of code that is defined once but can be executed or invoked any number of times. It makes the code reusable and understandable. Functions can be parameterized (i.e. Can accept arguments) or can be non-parameterized (i.e. no arguments can be passed to the function)

function add( num1, num2)    {
    return num1 + num2;
}

Function Declaration

A function declaration consists of three parts :

  • Identifier name or Function name -

    function multiply (num1, num2)    {
      return num1 * num2;
    }
    

    Here multiply is the name of the function. Whenever we have to reuse the code defined inside the function we can call the function name (that will be explained further in this article).

  • Arguments

You can pass zero or more arguments to the function separated by commas.

function multiply (num1, num2)    {
    return num1 * num2;
}

Here num1 and num2 are the two arguments passed to the function. This function is a parameterized function as it accepts arguments.

  • Block of code

A block of code is defined by a set of curly braces inside which there are one or more statement that specifies the task performed by the function

function multiply (num1, num2)    {
    return num1 * num2;
}

The statement return num1 * num2 is the main body of the function.

Arrow Function

In ES6, Arrow functions were introduced and they are the shorter way of writing a function than a regular function. It is a way to define a function without using a function keyword and have a comparatively compact syntax.

It is useful when you have to pass one function as an argument to another function. The arrow function uses the mathematical notion “ => “ to separate the function parameters from the rest of the function body. Arrow functions are more of an expression than a statement. The general way to define arrow function is :

const sum = (x ) => { return x * x };

To make it more compact, if the body of the function contains only a return statement, we can omit the return keyword and the curly braces.

const sum = (x) => x* x;

const output = () => “No argument function”; //Arrow function with no arguments

const output = num => num * num; // Arrow function with one argument

const add = (num1, num2) => num1 + num2; //Arrow function with more than one arguments

The arrow function is useful to use when we have to pass functions as arguments such as in some of the array methods like filter(), map() and reduce().

Regular function -

function square(num){
    return num * num ;
}

Arrow function -

const square = (num) => {return num * num};

OR

const square = (num) => num * num;

Invoking Functions

Once a function is defined, you have to invoke the function to execute. There are multiple ways of invoking a function :

  • Invoking function as function
  • Invoking function as a method
  • Invoking function as a constructor

Invoking function as function

When a function is defined in global scope, it is invoked directly as a function.

function perimeter(side1, side2){
        var perimeter = 2 * ( side1 + side2 );
return perimeter;
}
perimeter(2,3)     //12

Invoking function as a method

When a function is defined inside and object properties, it is invoked as a method.

var myObject = { 
    name : “John”,
    getName: function(){
        return this.name;
}
}
myObject.getName()    //John

Invoking function as a constructor

When a function invocation is preceded by the keyword new, then it is a constructor invocation.

const add= new function('a', 'b', 'return a + b');
// Call the function
add(2, 6);

A constructor invocation creates a new, empty object that inherits from the object specified by the prototype property of the constructor

Function Scope

The scope is useful to control the visibility or lifetime or accessibility of any variable or parameters outside the function. It reduces naming conflicts and provides automatic memory management. Functions can access any variable or other functions defined in the global scope.

function area(){
    const pi = 3.14;
    let radius = 20;
    let area = 2 * pi * r;
}

The function is defined in the global scope, so it can be easily accessed by other functions but the variables defined inside the function scope such as pi, the area can not be directly accessed by other functions.

Function Arguments and Parameters

The functions in javascript can be parameterized or non-parameterized. Javascript does not check the type of parameter values.

function function_name(parameter1, parameter2 … parameterN){
    // body of the parameter
}

The parameter is a one or more named variable passed into a function, whereas arguments are the actual value passed as input to a function.

In the example given below,

function perimeter(length, width){
    return 2 * (length + width);
{
perimeter(20,12);
perimeter(2.6, 7.8);

The named variables “length and width” are parameters of the function. The actual values 20 and 12 passed in perimeter(20,12) are the arguments passed as input. Using the arguments passed into the function, the function will calculate the value and return.

Non-parameterized functions are those functions in which no parameters are passed.

function print(){
    console.log(“Hello Javascript!”);
}

Standard built-in functions

Global functions :

eval() - The eval() function evaluates code represented as a string and executes it.

isFinite() - The isFinite() function determines whether a supplied number is finite.

isNaN() - The isNan() function returns a Boolean value that indicates whether a value is the reserved value NaN (not a number).

parseFloat() - The parseFloat() function converts a string to a floating-point number.

parseInt() - The parseInt() function converts a string to an integer.

Window functions:

alert() - Displays an alert dialog.

window.alert("Hello Javascript")

confirm() - Displays a dialog with a message that the user needs to respond to.

window.confirm("Is your favourite colour blue? ")

prompt() - Returns the text entered by the user in a prompt dialog.

window.prompt("Enter your age") // "23"

Array methods:

pop() - Removes the last element from an array and returns it.

const arr = [1,76,23,65,78,98] console.log(arr) // [1, 76, 23, 65, 78, 98]

arr.pop() //98 console.log(arr) // [1, 76, 23, 65, 78]

push() - Appends new elements to the end of an array.

arr.push(66)
console.log(arr) // [1, 76, 23, 65, 78, 66]

shift() - Removes the first element from an array and returns it.

arr.shift() console.log(arr) // [76, 23, 65, 78, 66]

unshift() - Appends new elements to the end of an array.

arr.unshift(7)
console.log(arr) // [7, 76, 23, 65, 78, 66]

reverse() - Reverses the elements in an array in place.

arr.reverse()

sort() - Sorts an array in place.

arr1.sort() // [23, 65, 66, 7, 76, 78]

indexOf() - Returns the index of the first occurrence of a value in an array arr.indexOf(66) // 2 arr.indexOf(1) //-1

Date methods:

Date( ) - The Date() returns a string representation of the current date and time.

const today = new Date() console.log(today) // Wed Apr 07 2021 12:32:25 GMT+0530 (India Standard Time)

getDate( ) - Gets the day-of-the-month, using local time.

today.getDate(); // 7

getDay() - Gets the day of the week, using local time.

today.getDay(); // 3

getFullYear() - Gets the year, using local time.

today.getFullYear(); // 2021

toLocaleString() - Converts date and time to a string by using the current or specified locale.

today.toLocaleString(); // "4/7/2021, 12:32:25 AM"

Math methods:

ceil() - Returns the smallest integer greater than or equal to its numeric argument.

Math.ceil(12.876) // 13 Math.ceil(34.123) // 35

floor() - Returns the greatest integer less than or equal to its numeric argument.

Math.floor(12.987) // 12 Math.floor(76.22) // 76

random() - Returns a random number between 0 and 1.

Math.random(); // 0.33171350098145513

power(x,y) - Returns the value of a base expression taken to a specified power. x — The base value of the expression. y — The exponent value of the expression.

Math.pow(2,5) //32

max() - Returns the larger of a set of given numeric values.;

Math.max(12,98,23,98.9) //98.9

min() - Returns the smaller of a set of supplied numeric values.

Math.min(23,11,89,-9) //-9