Javascript Functions

Working with functions in Javascript

What is a function?

A javascript function is representation of set of operations as a single unit. It can be reused to perform the same set of operations for different set of data.

advantages of a function

  • code reusability
  • better code maintainability

javascript function syntax

function name_of_function(param1, parm2, ...params){
    // statements
}

function to calculate a square value of a number

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

let result = square(5)

console.log(result);
// 25

It's a simple example of find the square of the number

function to find given item in an array

function isExists(item, arr){
    let result = false;
    for(i=0;i < arr.length; i++){
        let itm = arr[index];
        if(itm == item){
            result = false;
            break;
        }
    }
}

let fruits = ["apples", "oranges", "mango"];

let output = isExists("apples", fruits);
console.log(output);
// true
let output = isExists("onion", fruits);
console.log(output);
// false

let numbers = [1,2,3,4,5];
let output2 = isExists(4, numbers);
console.log(output);
// true

recursion in javascript function

The (factorial)[https://en.wikipedia.org/wiki/Factorial] function (symbol: !) says to multiply all whole numbers from our chosen number down to 1.

Examples:

4! = 4 × 3 × 2 × 1 = 24

7! = 7 × 6 × 5 × 4 × 3 × 2 × 1 = 5040

1! = 1

function nFactorial(n) {
    if (n < 0) {
        return;
    }
    if (n === 0) {
        return 1;
    }
    return n * nFactorial(n - 1);
}

console.log(nFactorial(4));
// 24
console.log(nFactorial(7));
// 5040
console.log(nFactorial(1));
// 1