Functions are reusable blocks of code that perform specific tasks. It helps to organize the code, make it more modular, and for code reusability.
- Defining functions
- Calling functions
- Function arguments and return values
- Function Scope and closures
- Arrow functions
The functions are usable before defining it.
Syntax:
function functionName(parameter1, parameter2, ...) {
// Function body (statements to be executed)
return value; // Optional: Returns a value
}
function greet(name) {
console.log("Hello, " + name + "!");
}
To use function in the JavaScript code, that need to be called where it is required.
Syntax:
functionName(argument1, argument2, ...);
greet("Kumar"); // Output: Hello, Kumar!
Arguments: Values passed to a function that accepts as parameter of it when it's called. Return Values: Values that a function can return to the where it was called or invoked using the return statement in the function.
function add(a, b) {
return a + b;
}
let sum = add(1, 2);
console.log(sum); // Output: 3
Scope: The region of code where a variable or function is accessible. Closures: Functions that have access to variables from the outer scope, even after the outer scope has finished executing.
function outerFunction() {
let x = 10;
function innerFunction() {
console.log(x); // Accesses the outer variable x
}
return innerFunction;
}
let closure = outerFunction();
closure(); // Output: 10
It is defined in a concise way or in shorthand form.
Syntax:
(parameters) => expression;
let greet = (name) => {
console.log("Hello, " + name + "!");
};