Functions in JavaScript

Functions in JavaScript

Function :

A JavaScript function is a block of code designed to perform a particular task.A JavaScript function is executed when "something" invokes it (calls it).A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses ().

The parentheses may include parameter names separated by commas:
(parameter1, parameter2, ...). The code to be executed, by the function, is placed inside curly brackets: {}.

Why JavaScript

  1. Code reusability: We can call a function several times so it save coding.

  2. Less coding: It makes our program compact. We don’t need to write many lines of code each time to perform a common task.

1. Function declaration :

function nameOfFunction (){
    //code 
}

For example

function helloWorld (){
    alert("Hello World...");
}

helloWorld() // function call

2. Function Expression :

Functions can also be defined as an expression,which can be stored in a variable. Simplly mean create a function within a variable and for calling function invoke variable.

let  nameOfFunction = function() {
    //code
}

For Example

let gm = function() {
    alert("Good Morning...");
}

gm()  //function call

3. Function Parameters and Arguments :

We can call function by passing arguments. Functions can take parameters as input, which can be used inside the function. The values passed to the function when it is called are known as arguments.

function sum(a, b){  //take parameters
    let total = a+b;
    console.log(total);
}

sum(5,4);  //pass arguments

4. Functions With Return value :

Functions can return a value using the return statement.We can call function that returns a value and use it in our program.

function add(a, b){
    let sum = a+b;
    return sum;  //return sum
}

console.log(add(5, 15));

5. Arrow function :

Arrow functions were introduced in ES6.Arrow functions allow us to write shorter function syntax:

let arrowFunction = () => {
    console.log("console in arrow function");
}

Happy Learning.