Understanding Functions in JavaScript
Ghloriey
Posted on May 24, 2023
Introduction
Are you a beginner in JavaScript seeking to understand the use of JavaScript functions and the various things you can accomplish using functions? Seek no more because you have found the answer.
Learn how to create functions in JavaScript using various methods, manipulate functions, use the return keyword, invoke or call a function, and the best practices for writing a function.
By the end of this article, you will get in-depth knowledge on how to use JavaScript functions to build dynamic websites with your codes looking more readable and organized. Let's begin!
Prerequisites
- Fundamentals of JavaScript, including declaring a variable and assigning a value to it.
- A code editor such as Visual Studio Code or Sublime Text
Creating Functions
JavaScript Function can be created using the built-in function
keyword followed by the function's name, a parathesis to contain the parameter(s), and a curly brace that holds the functions to be defined. There are two ways to define or create a function this includes;
Function Declaration:
Syntax
function functionName(parameter){
Block of statement to be executed
}
Example
function getAge(currentYear, birthYear){
let age = currentYear-birthYear
console.log(age)
}
The example above aims to calculate a person's age using function declaration in JavaScript. The function's name is getAge
which accepts two parameters: currentYear
and birthYear
. In this case, parameters are simply what the function requires from the user. The Javascript statement is written between the opening and the closing curly brace. In this case, the statement calculates a person's age by subtracting the birthYear
from the currentYear
and assigned to a variable age
.
Function Expression:
Syntax
let functionName = function(parameters){
Block of statement to be executed
}
Example
let getAge = function(currentYear, birthYear){
return currentYear - birthYear
}
The difference between the function declaration and expression is that the function declaration is defined using the function
keyword. In contrast, the function expression involves assigning the function to a variable or constant.
Function Execution
If you executed the first two codes above, you'd notice that neither logged any output to your console, which brings about what we call function execution.
It invokes or calls a function to perform a specific task or computation. This can be achieved using the function's name, followed by parenthesis()
, and should be written after the closing curly brace.
Looking back at the previous example, let's now call the function
//Defining the function
function getAge(currentYear, birthYear){
let age = currentYear-birthYear
console.log(age)
//Calling the function
getAge(2023,1995)// output 28
you can also decide to use the return keyword while writing the JavaScript statement and then logging the answer to the console while calling the function as seen below;
// Defining the function
let getAge = function(currentYear, birthYear){
return currentYear - birthYear
}
// calling the function
console.log(getAge(2023,1995))// output 28
Note that return isn't the same as console.log: return
stops the execution and returns a value, while console.log displays the output on the console. If you use the return keyword without the console.log
, your code will run, but no result will be displayed.
Functions Calling other Functions
Functions can be reused or called anywhere within your code at any time, and the most exciting thing is that even new functions can call or reuse a pre-existing function. Assuming we want to create a new function that checks if a person is eligible to vote by using his or her age. We can achieve that by creating a new function, checkEligibleVoters
, and calling the last function age within the function expression. Let's see how it works!
// pre-existing function
function getAge(currentYear, birthYear){
let age = currentYear-birthYear
return age
}
// new function
function checkEligibleVoters(age){
let currentAge = getAge(2023, 2015)// calling the previous function
if (currentAge >= 18){
console.log(`you're eligible to vote`)
}
else{
console.log(`sorry! you're too young to vote`)
}
}
checkEligibleVoters(getAge)// output: you're too young to vote
Arrow Function
The arrow function is a shorter way of declaring a function expression and is especially useful when writing short and concise functions.
Syntax
let getAge = (parameter1,parameter2)=>{function expression}
let's now write the previous example using the arrow function
let getAge = (currentYear,birthYear)=>{
return currentYear-birthYear;
}
console.log(getAge(2023,2005))// output: 18
// can still be further simplified
let getAge = (currentYear,birthYear)=>currentyear-birthyear
console.log(getAge(2023,2005))// output: 18
Built-in Functions and Methods in JavaScript
Numerous built-in functions for JavaScript are provided as part of the language. Because they are pre-installed in the JavaScript runtime environment and can be utilized immediately, they are frequently referred to as "global functions" or "built-in functions." The following are examples of commonly used JavaScript built-in functions:
-
Array()
: This function creates a new array object. -
string()
: This function converts values to strings. -
Boolean()
: This function converts values to Boolean. -
Number()
: This function converts a value to a number. -
Math.floor()
: This function rounds numbers down. -
Math.round()
: This function rounds numbers to the nearest integer. -
SetTimeout()
: This function is used for scheduling the execution of code after a certain delay or at regular intervals -
Math.ceil()
: This function rounds numbers up -
console.log()
: This function shows the result of execution on the console.
Best practices
- Use descriptive names: To make your code easier to read and maintain, give the names of your function that are relevant and descriptive. The name of a function should appropriately describe what it performs or does.
- Properly Document Your Functions: Use comments or documentation to describe the function's intent, expected input, return values, and possible side effects. This helps other developers understand and use your function correctly.
- Limit Function Complexity: Ideal functions should carry out a particular task or have a distinct and narrowly defined role. Create short, concise functions rather than long, complicated ones. A complex process can be broken down into more manageable, reusable functions to help with code organization and readability.
- Use Function Parameters: Instead of relying on global variables, pass data and values to functions through parameters. This improves the reusability of functions and makes the code more modular.
Conclusion
In summary, learning JavaScript functions is essential to mastering JavaScript development. Functions are a crucial language component, enabling you to encapsulate reusable code, solve problems, and create complex applications.
This tutorial covered the basics of JavaScript functions, including creating and calling a function using function declaration and expression, returning functions from other functions, using arrow functions, and some JavaScript in-built functions.
Remember to stick to best practices while writing your code and keep practicing and exploring the world of Javascript functions.
If you learned something from this article, please like and comment.
Credits
Posted on May 24, 2023
Join Our Newsletter. No Spam, Only the good stuff.
Sign up to receive the latest update from our blog.
Related
October 21, 2024