Functions in Javascript

Functions in Javascript.

Aisha Wahab O.
2 min readMay 2, 2024

--

Functions in Javascript are essentially reusable blocks of code that perform specific tasks. By creating functions, we can avoid writing the same code repeatedly. We can simply call the function whenever we need that specific task performed. They also help structure codes by grouping related functionalities together, making it easier to understand and maintain.

There’s also the principle called DRY “Do not Repeat Yourself”. The use of function helps solve this issue as well.

The basic structure of a function is : defining the function and calling the function. It goes as follows:

function greet()

{
console.log("Hello World");
}

greet();

//Hello World

Function Passing (Values) and Return.

Functions can return a value using the ‘return’ statement. It allows the function to send back a result or data after it has executed its code. The ‘return’ statement is followed by an expression or variable that specifies the value the function will return.

Example:

function greet()

{
return ("Hello World");
}

let string = greet ();
console.log(string);

//Hello World

It should be noted that a function can only have one ‘return’ statement. If no return statement is present, the function returns as ‘undefined’.

As for passing values, it allows us to create versatile functions that can operate on different data sets without needing to rewrite the entire function each time. We can also pass multiple values by separating each value with a comma.

Example:

function greet(user)

{
return `Hello ${user}!!`
}

let user = 'Aisha';
let string = greet(user);
console.log(string);


//Hello Aisha!!

Function Expression

We should know that Javascript treats function as an object type. Also, functions are not just building blocks for our code; they are themselves values. This means that we can assign functions to variables or use them within an expression.

Examples.

  1. Anonymous Function Expression
let sayHi = function() {
console.log("Hello!");
}

sayHi();

// Hello!
let add = function (num1, num2)
{
return num1 + num2
}

let result = add(9,2)

console.log(result);

//11

2. Named Function Expression

let calculateSum = function add(num1, num2) {
return num1 + num2;
}

const result = calculateSum(8, 11);
console.log(result);

//19

See you next time !

--

--

Aisha Wahab O.
Aisha Wahab O.

Written by Aisha Wahab O.

I currently write on JavaScript. .

Responses (1)