Engineering Blog

                            

Function in JavaScript

A function in JavaScript is similar to a procedure—a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.

We can separate function in two type in javascript:
i) Function declaration
ii) Function expression

Function Declaration

A function declaration tells the JavaScript engine about a function’s name, return type, and parameters. When a function has been declared, it can be used anytime inside a class or development scope whenever it’s been called/invoked.

function clacAge(birthYear){
 return 2037 - birthYear
}
const age1 = clacAge(1991)

Function Expression

The Javascript Function Expression is used to define a function inside any expression. The Function Expression allows us to create an anonymous function that doesn’t have any function name which is the main difference between Function Expression and Function Declaration.

const calcAge2 = function clacAge(birthYear){
 return 2037 - birthYear
}
const age2 = calcAge2(1991);

Actually “function clacAge(birthYear){ return 2037 – birthYear}” this is called expression. So the expression produce value. In JavaScript function are just value either string or number or boolean.

The practical difference between function declaration and expression is, we actually can call function declaration before they are defined.

function declaration:
const age1 = clacAge(1991)

function clacAge(birthYear){
 return 2037 - birthYear
}

But for function expression it will throw error:
function expression:
const age2 = calcAge2(1991);

const calcAge2 = function clacAge(birthYear){
 return 2037 - birthYear
}

Arrow Function

Arrow function was introduced in ES6 which is shoter and fater to write.

const example = () => console.log("example arrow function")

In JavaScript, an arrow function is a shorthand way of defining a function. They were introduced in ECMAScript 6 (ES6) and are often used as an alternative to traditional function expressions.

function add(a, b) {
  return a + b;
}
can be shortened to an arrow function:
const add = (a, b) => a + b;

One of the key advantage of arrow function is it has Lexical this keyword, which means it inherits this keyword from its surrounding context. In traditional function, this keyword could change based on how it is called.

Previous Post
Next Post