How to write functions in JavaScript?

Rahul Kumar
7 min readAug 17, 2023

--

Scopes, Built-in functions, Higher order function, First citizen function.

Content of this blog:

What is Function?

Function is a reusable block of code that performs a specific task.

Why to Use Functions?

  • Resuability of code.
  • Minimize boilerplate code.
  • It is used to decompose a problem into smaller chunks.
  • Eases the debugging and maintainablity of the code.
  • Abstract the details of the given problem.
  • To achieve Modularity.

Non-Modular Approach:

Modular Approach:

Divide and conquer approach:

How to use Functions?

Define a function keyword followed by the function name and body of the function.

Types of Function:

  1. Pre-defined: It is built-in function which is provided by ECMAScript.
  2. User-defined: It is defined by user according to problems.
  3. Anonymous: Function without name
  4. Callback: function which atleast one Anonymous function as argument.
  5. Closures: Acombination of a function bundled together with references to its surrounding states.

Function Declaration:

Declare a function in javaScript:

Syntax:

Example:

// function declaration
funtion add(num1,num2){
return num1+num2;
}
// function call
let result = add(1,2);

console.log("sum", result);

Declare a Anonymous Function:

Function without a name:

Higher Order Functions:

→ Function which either accept or return other functions are called Higher Order Functions. Many in-built functions in JS are Higher Order Functions.

greet is higher Order function.

Declare a Function Expression:

Example:

Why function in JavaScript is called as First Class Citizen?

→ Because, In JavaScript, Any object which can be assigned, passed as a parameter and returned from a function is called a First Class Citizen in a programming language. Thus, all functions are First Class Citizens in JS.

Function Closures:

a. Must be a Nested Function (i.e., Having a function within another function)

b. If the inner function is going to refer to the definitions which are there in the scope in which it is defined and

c. Outer Function must return an inner function then the function object will have a closure property

Example of Function passes as Parameter:

// function passed as a paramter
function welcome(){
console.log("Hello World");

}
function goodbye(){
console.log("See you later");

}

function greet(choice){
choice();
}

greet(welcome);
greet(goodbye);

/*
Output:
Hello World
See you later
*/

Function Parameters:

  • Default Parameters Helps to set a value to Parameters.
  • You can have more than one default parameters in JavaScript.
function multiply(num1,num2=1){
return num1*num2;
}

console.log(multiply(3,2)); // 6
console.log(multiply(4)); // 4

console.log(multiply(3,undefined); // 3
  • Function parameters can be also Destructured.
  • It will be useful when we will work on Objects and arrays as function parameters.
  • Example:
// Destructured Parameters - Array
function showDetails([arg1,arg2]){
console.log(arg1);
console.log(arg2);
}

showDetails([ "Rahul", "Razz", "Rohan" ]);
/** Output:
Rahul
Razz
*/

Example 2:

// Destructured Parameters - Object
function showDetailsOBj({ name, country }){
console.log(name);
console.log(country)
}

showDetailsObj({name: "Rahul", age: 25, country: "India" })

/** Output:
Rahul
25
*/

Arrow Functions:

  • Arrow Function is a concise way of writing a function.
  • Arrow Functions are actually anonymous functions as they don’t have a name for it.

Let’s create a Arrow functions:

function greet(choice){
choice();
}

// greet(function(){ console.log('Hello World') });

// another way of writing this: Arrow function
greet(()=>{console.log('Hello World')});

Different Ways to write arrow functions:

1. Arrow function with Multi parameter, multi line code.

example:

let calculateTripCost = (ticketPrice,noOfPerson) =>{
totalCost = ticketPrice * noOfPerson;
return totalCost;
}

console.log("Total Cost: ", calculateTripCost(1200,4));
// Total Cost: 4800

2. Arrow Function with No parameter, single line code.:

  • If the arrow function body contains only one line then no need to put curly braces for the function body.

example:

let trip = () => console.log('Lets go to trip');

trip(); // Lets go to trip

3. Arrow function with One parameter, single line code.

If an arrow function takes only one parameter then we need not to have even the small brackets surrounding them.

Example:

let trip = place => console.log('Lets go for trip ', + place);
trip('Paris'); // Lets go for trip Paris

let trip = _ => console.log('Lets go for trip ', + _ );
trip('Paris'); // Lets go for trip Paris

Variables Scopes:

  • Local Scope
  • Global Scope
  • Block Scope

Global Scope

  • A variable is said to be in global scope when it is accessible throughout the program, across functions, across files
  • The variable which is declared in global scope can be accessed inside local access.

Local Scope

  • Local scope is when a variable is accessible only within a function. This is also called function scope.
  • The variable which is declared in local scope can not be accessed outside the local access.

Always create variable with let keyword, if you don’t use it it will act as global variable.

example:

JavaScript first finds the variable in same scope.

example:

You can see in above example, the value of global variable is printed.

As you can see the output first it find the variable in local scope if it is there then value of that will be printed.

Block Scope Variable:

the variable which is declared inside a block that is accessible inside that block only. that’s why In above example, the value of globalVar is printed from global scope.

Now You can see the block scope variable is accessed.

Summary:

  • A Variable which is declared in a block is called Block Scoped Variables. It is accessible inside that block only where it is declared.
  • A Variable which is declared inside a function is called Local Scoped Variable. It is accessible inside that function and block(means in Local Scope).
  • A Variable which is outside of block and local scope is called Global Scoped Variable. It is accessible from anywhere.

Built-in Functions/ Pre-defined Functions:

eval():

example:

parseInt():

Parses the string argument and extracts the integer.

parseFloat():

Parses the string argument and extracts the Float.

isNaN(): (not a number)

example:

isFinite():

example:

NaN is not finite so Its False.

Number():

It is constructor of Number class.

If It is unable to converts then It will return NaN.

String():

It is also a Constructor.

Example:

--

--