Sitemap
Njagua Nyingi Kevin

Njagua Nyingi Kevin

FUNCTIONS IN JAVASCRIPT

4 min readJan 10, 2025

--

Press enter or click to view image in full size
source: Google

Functions allow us to define a code block we can call and execute whenever.

Think of a Function as a box with some code inside it that does something particular.

This is how we call/invoke a function — function scores will be called this way

scores()

we can call a function as many times as we want.

Functions help us to write bits of code that are reusable.

DIFFERENT WAYS OF CREATING A FUNCTION

A: Function Declaration

keyword is function & then give the function a name, as we do with variables.

function greet() {
return "Hello there!";
}
console.log(greet()); // Calling/Invoking a Function
greet(); // we must call a function

B: Function Expression

This is creating a function by storing it in a variable.

This time the function has no name since now the name is the variable name.

NB: Anytime you create a variable and set it equal to something, such as a function, string, number, etc., that is known as an expression.

At the end of an expression we usually put a semi-colon.

const speaks = function () {
return "Good morning!";
};
console.log(speaks());

HOISTING IN JAVASCRIPT

This is calling/invoking a function before the function.

This works with a function declaration.

BUT not with Function expressions.

WHEN DECLARING FUNCTIONS, I 99% PREFER MOST OF THE TIME TO USE FUNCTION EXPRESSIONS.

ARGUMENTS AND PARAMETERS

Parameters passed with values as shown below are default values.

Useful just in case you forget to pass an argument to a function while calling it.

Parameters have a local scope and are only accessible within the function.

The order of arguments passed to a function must match the order of parameters.

const speak = function (name = "kev", time = "night") {
return `Good ${time} ${name}`;
};
console.log(speak("Zahra", "morning"));
console.log(speak()); //default values are used

Returning Values

When a function returns a value what we need to do is store the value in a variable so that we can use it later.

This provides global scope and now we can use the return value anywhere.

const calcArea = function (radius) {
let area = 3.14 * radius ** 2; // local scope
return area;
};
const area = calcArea(10); // global scope. we are storing the return value here
console.log(area);

We are simply;

calling a function

Returns the area

CODE CLEAN UP

No need for a local variable to return the area.

Store area in a global variable — can be accessed anytime.

const calcArea = function (radius) {
return 3.14 * radius ** 2;
};
const theArea = calcArea(10);
console.log(theArea);
const calcVolume = function (theArea) {
return theArea * 4;
};
console.log(calcVolume(theArea));

C: ARROW FUNCTIONS

Modern Way of Writing Functions.

Get Njagua Nyingi Kevin’s stories in your inbox

Join Medium for free to get updates from this writer.

I’ll use the functions above but I will switch the names a bit

We do not use the function keyword.

It is a shorter way to create a regular function.

const area = (parameters) => {code block};

If we have a single return line we can take away the return keyword & remove the curly braces as shown below;

NB: THERE ARE TIMES THE ARROW FUNCTION CAN NOT BE USED(EG FOR EACH METHOD)

const calcAreas = (radius) => 3.14 * radius ** 2;
const areas = calcAreas(10);
console.log(areas);

PRACTICE ARROW FUNCTIONS

const greetV = () => "hello ms. valentine";
const greetResults = greetV();
console.log(greetResults);
const bill = (products, tax) => {
let total = 0;
for (let i = 0; i < products.length; i++) {
total += products[i] + products[i] * tax;
}
return total;
};
totalTax = bill([10, 15, 30], 0.2);
console.log(totalTax);

FUNCTIONS vs METHODS

Both functions and methods are used to perform a specific task.

A FUNCTION IS A BLOCK OF CODE THAT CAN BE INVOKED

Functions are invoked directly.

Functions are used when we want to reuse the code.

Functions are defined on their own while

Methods are defined in an object or data type

const name = () => "Hi Kevin"; // fn defined on its own
let result = name();

A METHOD IS STILL A FUNCTION

Methods — Functions used in a specific data type EG STRING, OBJECT ETC

invoked using dot notation(.length(), .toUpperCase(), .includes())

Methods can be defined inside an object, regular functions cannot

let name = "kevin";
name.toUpperCase(); //METHOD INVOKED & method defined on a string

The difference between methods and functions is how they are INVOKED

Foreach Method & Callbacks

Callbacks — This is when we pass a function as an argument.

- The passed function is called a callback function.

Using a method in combo with a function

FOREACH METHOD — It is a method that iterates over an array

- It is a bit like a loop but it is more elegant

- The method expects a callback function as an argument

NB: A callback fn can take a 2nd parameter for the index

let myPeeps = ["Zahra", "Valentine", "Jane", "Makena", "John"];
myPeeps.forEach((person, index) => {
console.log(`${index} - My name is ${person}`);
});

OPTION 2 OF WRITING CALLBACK FNS

IF THE FUNCTION IS BIG

let men = ["John", "James", "Bob", "Luka"];
const logPerson = (person, index) => {
console.log(`${index} - Hi ${person}`);
};
men.forEach(logPerson);

Callback functions in action

Adding an array of names into an HTML template & outputting it on the browser.

I have added an ul in the body with a class named people.

You have to create an empty variable outside of the callback function

for storage purposes

It can be accessed by the callback function since it’s a global variable.

const ul = document.querySelector(".people");
const people = ["John", "James", "Bob", "Luka", "chunli"];
let myHtml = ``;
people.forEach((person) => {
//create html template
myHtml += `<li style="color: red">${person}</li>`;
// the += is for adding each iteration to the empty variable
});
console.log(myHtml);
ul.innerHTML = myHtml;
/*

--

--