Functions are blocks of reusable code. Here's an example of declaring and invoking a function:
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("John"); // Output: "Hello, John!"
Functions can have parameters, which act as placeholders for values passed as arguments. Example:
function add(a, b) {
return a + b;
}
let sum = add(3, 5); // sum equals 8
The return statement is used to specify the value returned by a function. Example:
function multiply(a, b) {
return a * b;
}
let result = multiply(4, 6); // result equals 24
Variables in JavaScript have either global or local scope. Example:
let globalVariable = "I'm global";
function myFunction() {
let localVariable = "I'm local";
console.log(globalVariable); // accessible
console.log(localVariable); // accessible
}
console.log(globalVariable); // accessible
console.log(localVariable); // not accessible
Functions can also be assigned to variables or written as arrow functions. Example:
let greet = function(name) {
console.log("Hello, " + name + "!");
};
let multiply = (a, b) => a * b;