In this section, we cover functions, what they are utilized for and how to keep in touch with them. A function is a way to encapsulate a portion of your code so a specific action can e reused and called on to run at a specific time.
Declaration
An example of what the syntax to declare a function looks like.
function name (parameterrs) {
// function body goes here
}
// example
function showMessage() {
alert("hello world");
}
Note: A parameter is a named variable passed into a function while function arguments are the actual values assigned to the parameters.
Naming
Since the functions are actions, their name is usually a verb. Keep the names brief but accurate to describe what the function does.
showMessage();
// shows a message
getAge();
// returns the age
calcSum();
//calculted a sum and returns the result
createForm();
// creates and returns a form
checkPermission();
// check a permission, returns true/false
Arguments
A function can require you to pass some arguments(Args) which act as a variable within the function. This allows for better reusability.
function calcAge(currentYear, birthYear) {
return currentYeay - birthYear;
}
const rahAge = calcAge(2021, 2004);
// output: 17
const samAge = calcAge(2021, 2000);
// Output:21
Local variable
A variable declared inside a function will only be visible within the scope of the function.
function showMessage() {
let message = "Hello World";
// local variable
alert(message);
}
showMessage();
// Hello World
alert(message); // error
// the variable is local to the function.
Return a value
A function can return a value- usually one generated or manipulated by the function code.
const movieAgeLimit = 10;
function checkAge(age) {
if (age >= movieAgeLimit) {
return true;
} else {
return false;
}
// alternative: return age >= moveAgeLimit
}
const hasAccess = checkAge(18);
if (hasAccess) {
alert("enjoy the movie");
} else {
alert("Get out please!");
}
Call another function
It can be also used to perform an action or call another function.
const yourName = prompt("What is your name? ");
function showWelcomeMessage(name) {
alert(`Welcome ${name}`);
}
showWelcomeMessage(yourName);
👓Wrapping
Function names tend to be verbs to easily describe what the function does. Arguments are values you can pass to be used within a function. Variables declared within a function are only visible within the function scope. A scope can return a value or call another function / action. Use functions to store re-usable code that can be called as and when needed.
Thank you For reading ⚡
Removal.AI - [SPONSOR]
Remove background from multiple images in a single upload straight to your desktop using Bulk Photo Background Remover for Windows.
- ✅ Drag & Drop Multiple Images
- ✅ Optimize Product Images
- ✅ Select Your Background
- ✅ Set Your Output Size
- ✅ Exceptional Results
Visit -> Removal AI