In JavaScript, functions are blocks of reusable code. They allow you to bundle functionality, make it more readable, and avoid repetition. Here's a brief tutorial on writing an arrow function in JavaScript.
const functionName = (params) => {
// code to be executed
}- const: const should be used whenever a function expression is assigned to a variable.
- The function name: The name you choose for the function.
- Parameters: Optional comma separated parameters. This is the data passed into the function. If there are no parameters, the () is still required.
- The arrow syntax: Indicates that this will be a function.
- The body: The statements that make up the function itself. Surrounded by curly braces.
Example:
const greet = (name) => {
console.log("Hello, " + name + "!");
}Tip: Functions often perform actions, so naming with a verb can make it clear what the function does. Examples include:
fetchData( ),calculateArea( ), orprintReport( ).
To execute the function, you call or invoke it by using its name followed by parentheses.
Example:
greet('Alice'); // Outputs: Hello, Alice!Functions can process data input and output a value using the return keyword.
Example:
const addNums = (numA, numB) => {
return numA + numB
}
const total = addNums(2, 4);
console.log(total) // Expected value: 6For more information on functions and how they are used in JS, check out the MDN docs.
-
Create a new file with a
.mdextension. -
Choose a new topic, we’ve provided a few for inspiration:
- How to write an HTML Boilerplate
- The anatomy of a CSS selector
- How to create a file using the Terminal
- How to build the perfect sandwich
-
Practice your new skills by writing another short tutorial in Markdown!