Functions can be declared using the function
keyword.
Functions are executed (or invoked) by using their name followed by parentheses.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Vignesh"); // Hello, Vignesh!
Parameters: Variables listed in a function's declaration. They act as placeholders for values.
Arguments: Values passed to a function when it is invoked.
Functions can return a value using the return
keyword. If no return
statement is present, the function returns undefined
.
function add(x, y) {
return x + y;
}
let sum = add(5, 4);
console.log(sum); // 9
A closure is formed when a function is defined within another function.
function outerFunction() {
let outerVariable = 'I am from the outer function';
function innerFunction() {
console.log(outerVariable);
}
return innerFunction;
}
let closureExample = outerFunction();
closureExample(); // I am from the outer function