Functions in JavaScript 101

Tevfik
5 min readMar 12, 2023

--

Mathematical functions and functions in programming languages share some fundamental similarities. Just as mathematical functions take inputs, perform operations, and produce outputs, functions in programming languages take parameters, execute code, and return values. Both types of functions are used to perform specific tasks and help break complex problems down into smaller, more manageable pieces. However, while mathematical functions are used primarily to solve equations and make calculations, functions in programming languages can be used for a wide variety of purposes, from manipulating data to controlling program flow. In this article, we’ll explore the basics of functions in JavaScript and how they can be used to build powerful and flexible programs.

Functions in JS

Functions are one of the fundamental building blocks in JavaScript. A function in JavaScript is similar to a procedure — a set of statements that performs a task or calculates a value, but for a procedure to qualify as a function, it should take some input and return an output where there is some obvious relationship between the input and the output.[1] Function declaration starts with the ‘function’ keyword after that you define the function’s name then open braces and list parameter names in it after that you write your function body in curly braces. Here is an example that helps us to better understand.

function greet(name) {
console.log(`Hello world!, my name is ${name}`);
}

In the above example, we defined a function whose name is greet and it takes one parameter which is name . The function logs simply one sentence with a given name.

When we call this function,

greet("Tevfik") //logs 'Hello world!, my name is Tevfik'

We write just a function’s name with a chosen parameter and our function logs our sentence out.

We have several types of function parameters. The first one function with regular parameters.

function addNumbers(x, y) {
return x + y;
}

const sum = addNumbers(3, 4); // Returns 7

The second one is a function with default parameters.

function multiplyNumbers(x, y = 1) {
return x * y;
}

const product1 = multiplyNumbers(3, 4); // Returns 12
const product2 = multiplyNumbers(3); // Returns 3

In the above example, we set a default value for a parameter y which is 1 and at the product2 function we don’t define parameter y but it has a default value of 1 and take it for a value.

The third one is a function with rest parameters.

function sumNumbers() {
let numbers = Array.prototype.slice.call(arguments);
return numbers.reduce(function(total, number) {
return total + number;
});
}

const sum = sumNumbers(1, 2, 3, 4, 5); // Returns 15

In this example, the sumNumbers function uses the arguments keyword to get all of the arguments passed to the function and converts them into an array using the Array.prototype.slice.call() method. It then uses the reduce method to add up the values in the numbers array and return their sum.

we have a fourth type of function type which is a function with named parameters.

function printPersonInfo({ name, age, address }) {
console.log(`Name: ${name}, Age: ${age}, Address: ${address}`);
}

const person = { name: "John", age: 30, address: "123 Main St" };
printPersonInfo(person); // Output: Name: John, Age: 30, Address: 123 Main St

When the function is called with the person object as an argument, the object's properties are automatically assigned to the corresponding parameter variables.

The last type of parameter is destructured parameters,

function printBookInfo({ title, author, year }) {
console.log(`Title: ${title}, Author: ${author}, Year: ${year}`);
}

const book = { title: "The Catcher in the Rye", author: "J.D. Salinger", year: 1951 };
printBookInfo(book); // Output: Title: The Catcher in the Rye, Author: J.D. Salinger, Year: 1951

When the function is called with the book object as an argument, the object's properties are automatically assigned to the corresponding parameter variables. The function then logs a string with the book's information to the console.

Now that we’ve covered the parameters, let’s turn our attention to the argument. An argument in JavaScript is a value that is passed into a function when the function is called. The function can then use the value of the argument in its calculations or operations. In the first example, we declared a function greet where we called a function with my name. In that example, my name is an argument. For clarify,

function calculateTotalPrice(price, taxRate, discount = 0) {
const taxAmount = price * (taxRate / 100);
const discountAmount = price * (discount / 100);
const totalPrice = price + taxAmount - discountAmount;
return totalPrice;
}

const price = 100;
const taxRate = 20;
const discount = 10;

const totalPrice = calculateTotalPrice(price, taxRate, discount);
console.log(totalPrice); // Output: 108

In this example, the calculateTotalPrice function takes three arguments: price, taxRate, and discount, with discount having a default value of 0 .

Last topic of this section is return statements and return values.In JavaScript, a return statement is used to specify the value that a function should return when it is called. The return statement ends the execution of the function and sends a value back to the calling code.

For example, consider the following function that adds two numbers together:

function addNumbers(x, y) {
const sum = x + y;
return sum;
}

In this function, the return statement is used to specify that the function should return the value of the sum variable when it is called. The return statement also ends the execution of the function, so any code that comes after the return statement will not be executed.

When a function returns a value, that value is called the return value. In the example above, if we call the addNumbers function with the arguments 2 and 3, it will return the value 5. We can then store this value in a variable or use it in other parts of our code:

const result = addNumbers(2, 3);
console.log(result); // Output: 5

It’s worth noting that not all functions need to have a return statement. If a function doesn’t have a return statement, it will return undefined by default. Additionally, a function can only return one value, but that value can be a primitive value (like a number or a string) or an object.

That concludes our overview of the basics of JavaScript functions. In the upcoming parts, we will explore some more advanced concepts, such as function expressions, higher-order functions, and call-back functions and etc… Keep watching for more information and examples!

Resources:

  1. https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Functions

--

--

Tevfik

Mathematician || Software Developer || Blockchain&Cryptography enthusiast