Prerequisite: This document is basic enough, but to understand it well, you should have a good knowledge of variables and simple logic in Javascript, and you should have an integrated development environment (IDE) such as Vs Code, Sublime Text, or a browser's console to follow along.
Introduction
Functions are a very important part of programming because they are reusable blocks of code. In Javascript, Functions are no different from other languages in that they are reusable and are used to perform specific tasks. The syntax for Functions in Javascript is different from other programming languages like Python. In this article, you will learn how to write functions that work in Javascript.
What are Functions in javascript?
Functions are reusable blocks of code that return something. Don’t be confused by the last statement. The value a function returns might vary from an integer to a boolean, and yes, a function can return undefined or null (nothing). When a function returns no value or result, it is called a void function.
Types of functions:
Built-in functions: These are functions that are native or built into javascript, such as prototypes for data types like array.map(), object.keys(), string.toUpperCase(), etc.
User-defined functions: These functions are written by the programmer and not built into Javascript.
The other types below might be a little confusing, some will be explained in this article but others are for advanced topics in javascript.
Recursive functions: These are user-defined functions that are called inside themselves. They are used to solve problems that are smaller instances of the same problem.
Anonymous functions: These are functions without names; they are usually single-line arrow functions.
Higher-order functions: these functions take another function called a callback function as an argument.
Constructor functions are used to initialize object properties in object-oriented programming (OOP).
The list goes on, and as you advance in Javascript programming, you will come across more. Going back to learning about user-defined functions.
Writing functions in javascript
For functions to work in Javascript, they have to be declared or written and then called. If a function is called before it is written, the program will run into an error during execution. This is because, in JavaScript, codes are executed from top to bottom. During execution, the Javascript engine encounters the function call and checks if it has seen any familiar function declaration with the same name; if it doesn't see one, it throws an error. Ok, back to the function declaration.
Function declaration
You should be familiar with variable declarations. User-defined functions have to be declared too. Here’s how to declare a function in Javascript:
//Use the function keyword to declear a function
function functionName(){
//your code goes inside here
}
While writing a function declaration, you can pass a parameter(s) into the function like this:
function functionName(parameter){
}
//A function that adds too numbers
//parameters are seprated with comma's
function addTwoNumbers(a, b){
return a + b;
}
//A function that checks a parameter's length and returns 0 or 1
function checkLength(string){
let strings_length = string.length;
let what_to_return;
if(strings_length > 10){
console.log(`${string}'s length is lesser than 10`);
what_to_return = 0 ;
} else {
console.log(`${string}'s length is greater than 10`);
what_to_return = 1 ;
}
return what_to_return;
}
Another type of function in Javascript is called the arrow function. During deceleration there's an omission of the "function" keyword; the addition of an equal sign before the parenthesis and an arrow after.
functionName = (parameter) =>{
//your code goees here
}
//an arrow function that welcomes the user
welcomeMessage = (username)=>{
console.log(`Welcome back ${username}`)
}
Calling Functions
Calling a function should come after declaring the function; it's like triggering the function into action. To call a function, write out its name with a set of parentheses on the right side of the function's name. Try this in your editor or browser:
//sythax
functionName(argument);
//declearing the function
welcomeMessage = (username)=>{
console.log(`Welcome back ${username}`)
}
// call the function
let username = "titobi"
welcomeMessage(username);
//Output :Welcome back titobi
Instead of a parameter(s), you pass an argument(s) into a function when calling it. You can pass any argument into a function, ranging from variables to functions. When functions are passed as arguments, they are called callback functions, and they can be anonymous in nature, meaning without a name.
//
function addTwoNumbers(a, b){
return a + b;
}
function multiplyByTwo(callback,a,b){
//the callback called add is been called inside this function
let multiple = 2 * callback(a,b);
console.log(multiple);
return multiple;
}
// passing the addTwoNumbers as argument
multiplyByTwo(addTwoNumbers,1,5);
//Output:12
In the example above, the `multiplyByTwo` function is a high-order function, which means it takes in another function, the callback, as an argument. This happened while calling the `multiplyByTwo` function:
The `multiplyByTwo` function takes the `addTwoNumbers` function as an argument in place of the `callback` parameter, with two extra arguments of " 1 and 5".
The `addTwoNumbers` is called inside the `multiplyByTwo` function with arguments "1 and 5" passed into it. The result is multiplied by 2 and set to a variable called `multiple`.
The variable multiple was printed to the console and returned to the function `multiplyByTwo`.
Examples of high-order functions that take anonymous functions are the built-in functions array.map(), event listeners such as onClick(), etc.
onClick(callback)
//example
onClick(()=>console.log('I just got clicked'));
array.map(callback)
//example of a array
const numbers = [1, 2, 3, 4, 5];
const squaredNumbers = numbers.map((num) => num * num);
console.log(squaredNumbers); // Output: [1, 4, 9, 16, 25]
In both examples, both callbacks are anonymous functions meaning they have no names
Quiz
Write a function that takes two parameters, subtracts the lesser from the greater, and logs the result to the console.
Conclusion
As you advance your skills in Javascript, you will become accustomed to different types of functions, event handlers, and many more. You can read more about advanced functions here.