Understanding Functions
Functions in JavaScript are blocks of code designed to perform a particular task. They are fundamental to writing clean, maintainable, and reusable code. A function is executed when it is called (or invoked), rather than when the script is loaded.
Functions can take parameters, which are used to pass data into the function, and they can return a value. In JavaScript, functions can be defined in several ways, including function declarations, function expressions, and arrow functions introduced in ES6.
Defining a Function
function sayHello() {
console.log('Hello!');
}
Calling a Function
To call (or invoke) a function, you use the function name followed by parentheses:
sayHello(); // Outputs: Hello!
Function with Parameters
Functions can also take parameters, which allow you to pass information to the function:
function greet(name) {
console.log('Hello ' + name + '!');
}
Calling the function with a parameter:
greet('Alice'); // Outputs: Hello Alice!
Function that Returns a Value
A function can return a value that can be used in other parts of your code:
function add(a, b) {
return a + b;
}
console.log(add(5, 3)); // Outputs: 8
Arrow Functions
With ES6, JavaScript introduced arrow functions, a concise way to write functions. Here's how you write an arrow function equivalent to the add function:
const add = (a, b) => a + b;
console.log(add(10, 5)); // Outputs: 15
Understanding how to define and use functions is crucial for JavaScript programming, as it helps to structure your code more effectively, making it easier to debug and maintain.
Try it Yourself
Result:
Test Your Knowledge: JavaScript Functions
What does a function in JavaScript typically use to receive input?