How to write functions in JavaScript?

Rahul Kumar
6 min readAug 17, 2023

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

Content of this blog:

Function Declaration:

First way to Declare a function in javaScript:

funtion add(num1,num2){
return num1+num2;

let result = add(1,2);

console.log("sum", result);

2nd way to Declare a function in JavaScript using Anonymous Function:

function without a name.

Function which either accept or return other functions are called Higher Order Functions.

greet is higher Order function.

3rd way by Function Expression:

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

Example:

  • The variable which is declared in global scope can be accessed inside local access.
  • 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:

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:

--

--