How to Create Functions in JavaScript
Code Playground is only enabled on larger screen sizes.
In a real-world project, you may have pieces of code for different purposes.
For instance, you could have a piece of code asking the user to provide an input, another piece of code processing the user request, and so on.
If not organized appropriately, future maintenance would become a nightmare.
Not only because it is very easy to lose track, but also because there is no way to reuse your code.
Luckily, there is a fix, functions.
Function is a way for you to organize and reuse pieces of your code. It can be created with the function keyword, as demonstrated below:
function countEven(arr) {
let n = 0;
for (let e of arr) {
if (e % 2 === 0) {
n++;
}
}
return n;
}This function takes an input:
function countEven(arr) {
let n = 0;
for (let e of arr) {
if (e % 2 === 0) {
n++;
}
}
return n;
}Does something with the input:
function countEven(arr) {
let n = 0;
for (let e of arr) {
if (e % 2 === 0) {
n++;
}
}
return n;
}And finally return a result:
function countEven(arr) {
let n = 0;
for (let e of arr) {
if (e % 2 === 0) {
n++;
}
}
return n;
}To call the function, use its name, and followed by a pair of parenthesis where you can provide the function input.
function countEven(arr) {
let n = 0;
for (let e of arr) {
if (e % 2 === 0) {
n++;
}
}
return n;
}
let arr = [1, 2, 3];
console.log(countEven(arr)); // -> 1console.log("Hello, World!");