Member-only story
Here’s a comprehensive guide on JavaScript functions that covers essential concepts, from the basics to advanced usage:
Not a Medium member? Read this article here
1. What is a Function in JavaScript?
A function is a block of reusable code designed to perform a specific task. Functions allow you to organize and structure your code efficiently, making it more modular and easier to maintain.
Syntax:
function functionName(parameters) {
// Code to be executed
}
Example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('Alice'); // Output: Hello, Alice!
2. Function Types in JavaScript
JavaScript offers several ways to define functions:
a. Function Declaration
A standard way to define a function using the function
keyword.
Example:
function add(a, b) {
return a + b;
}
b. Function Expression
A function can be assigned to a variable, and this is called a function expression.