Understanding the Basics of JavaScript Functions

Understanding the Basics of JavaScript Functions

What are Functions ?

• Functions are the fundamental building block for structuring and executing code in JavaScript applications.

• Functions allows you to encapsulate a set of operations, improve code reusability.

Function Declaration

Defines a function with a name. The function can be called before its definition because of its hoisting behavior.

Hoisting is a javascript behaviour that transfer the declaration of function, variable declaration using varto the top of its scope.

// syntax

function function_name(arguments){
    // statements
}
function_name(arguments) //invokation
// example
function sum(a,b){
    console.log(a + b) // 30
}
sum(20,10)

/* EXPLANATION :->
we declare a function name as `sum` the function will accept two 
arguments everytime we try to invoke them. And inside function it will
print the sum of those two variable. On the time of invokation
we call the function by its name and pass the values in parenthesis 
according to the number of arguments will the function accepts.
*/

Function Expression

Defines a function as an expression. This approach is not hoisted, so the function must be defined before it can be used.

// example
const fun = function (a,b){
    return a * b
}
fun(20,10)

/* EXPLANATION 
we store the function in a variable and now the function will be invoke 
from then name of the variable. as if we want to store the value we 
need to use return statement. so that the function do calculation inside
it and the output store at the fun variable.

Arrow function

A shorter syntax introduced in ES6. Arrow functions have lexical this binding and are often used for shorter inline functions.

const fun = (a,b) => {
    return a + b
}
// OR
const fun2 = (a,b) => a+b

If you want more such content then make sure to following me on all available platform

Instagram

LinkedIn

Hashnode


Thank you for reading 🤍

Written By Mohit Soni