Functions are an important concept in JavaScript and are used to organize and reuse code. A function is a block of code that can be executed multiple times by calling it by its name. Functions can take parameters as input and return a value or nothing.
1. Function Declaration:
Functions can be declared using the function
keyword followed by the function name, a pair of parentheses, and a pair of curly braces.
function nameOfFunction() {
// code to be executed
}
For example,
function greet() {
console.log("Hello World");
}
greet(); // Output: Hello World
2.Function Expression:
Functions can also be defined as an expression, which can be stored in a variable.
let nameOfFunction = function() {
// code to be executed
}
For example,
let greet = function() {
console.log("Hello World");
}
greet(); // Output: Hello World
3.Arrow Function:
JavaScript ES6 introduced a new shorthand syntax for function expressions, called the arrow function.
let nameOfFunction = () => {
// code to be executed
}
For example,
let greet = () => {
console.log("Hello World");
}
greet(); // Output: Hello World
4.Parameters and Arguments:
Functions can take parameters as input, which can be used inside the function. The values passed to the function when it is called are known as arguments.
function add(num1, num2) {
console.log(num1 + num2);
}
add(10, 5); // Output: 15
5.Return Statement:
Functions can return a value using the return
statement.
function multiply(num1, num2) {
return num1 * num2;
}
console.log(multiply(10, 5)); // Output: 50
In conclusion, functions are a powerful tool in JavaScript that allow you to organize and reuse code. Understanding how to declare and call functions, use parameters and return values, is essential for writing efficient and effective code.