Sitemap

Creating a Function — JavaScript

2 min readJan 28, 2025

--

To create a function, we use the function keyword followed by the function name and parentheses. Functions are a way to group code together.

Press enter or click to view image in full size

When we call a function like greeting(), it is called "invoking a function" or "calling a function".

When we do this, it is called “declaring a function” or “defining a function”

function greeting() {
console.log('Hello')
}

Parameters

We can use parameters in functions to allow the user to input specific data when calling the function. They are the names of variables used to pass data into a function.

Arguments

Get Dinusha Somarathne’s stories in your inbox

Join Medium for free to get updates from this writer.

Arguments are the values that are passed into the function.

Press enter or click to view image in full size

Returning a value

function substract(x, y){
return x - y;
}

When we call the subtract(20, 10) function, we don't see anything written on the console because we didn't use console.log here. We only return an expression.

Press enter or click to view image in full size

The code console.log('After the return keyword') will not execute. Anything you put after the return keyword will not be executed because you essentially end the function and returnto the parent scope.

We can use console.log to display the value in the console.

Press enter or click to view image in full size

Usually, we do something with the return value, like store it in a variable

const value = subtract(40, 20);

You can also use return without a value, which is helpful for functions that don't need to return anything. For example, you might have a function that updates or deletes data on a server but doesn't require returning a value.

--

--