Functions..

Ishav Bhatt
September 3rd, 2019 · 1 min read

All about JavaScript functions…

What is fuction ?

Basically, We used JavaScript function to perform operations. We can call JavaScript function many times to reuse the code. Generally, Functions is a “subprograme” or a reuseable piece of code that is designed to perform a particular task. It is a series of statements called function body. We can passed the values to a function and the function return a value.

Advantage of JavaScript function..

There are mainly two advantages of JavaScript functions.

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

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

JavaScript Function Syntax

The syntax of declaring function is given below.

1function functionName([arg1, arg2, ...argN]){
2 //your code here
3}

Function that does not take a parameter and doesn’t return anything.

1function sayHello () {
2 console.log("Hello !");
3}

The above function does not take a parameter and doesn’t return a value;

A function that take a parameter but does not return anything.

1function log (message) {
2 console.log (message);
3}

The above function takes one parameter, named message, and logs the value to the console, and it return nothing.

If the function doesn’t return any value explicitly, then by default it returns “undefined”

A function that takes a parameter and returns a value.

1function square(number) {
2 return number * number;
3}

console.log(square(2)); The output of the above function is 4.

Most used functiion..

. Function Declaration

A function declaration is made of function keyword, followed by an function name, a list of parameters in a pair of parenthesis (para1, …, paramN) and a pair of curly braces {…} that defines the body code.

1// function declaration
2function isEven(num) {
3 return num % 2 === 0;
4}
5isEven(24); // return true;
6isEven(11); // return false;

function isEven(num) {…} is a function declaration that defines isEven function, which determines if a number is even or not.

. Function expression

A function expression is determined by a function keyword, followed by an optional function name, a list of parameters in a pair of parenthesis (para1, …, paramN) and a pair of curly braces { … } that defines the body code.

1var getRectArea = function(width, height) {
2 return width * height;
3}
4
5console.log(getRectArea(3,4));
6// output: 12

. Arrow function

An arrow function is defined using a pair of parenthesis that contains the list of parameters (param1, param2, …, paramN), followed by a fat arrow => and a pair of curly braces {…} that defines the body statements.

1const absValue = (number) => {
2 if (number < 0) {
3 return -number;
4 }
5 return number;
6}
7absValue(-10); // => 10
8absValue(5); // => 5

More articles from Ishav Bhatt