Understanding Core Functions
Functions are fundamental building blocks in programming. They allow you to group a series of statements to perform a specific task. This makes your code more organized, reusable, and readable.
What is a Function?
A function is a block of organized, reusable code that is used to perform a single, related action. Functions provide better modularity for your application and a high degree of code-reusing ability.
Defining and Calling Functions
You define a function with a name, followed by parentheses. Inside the parentheses, you can specify parameters that the function accepts. The code to be executed is placed inside curly braces.
// Example of defining a function
function greet(name) {
console.log("Hello, " + name + "!");
}
// Example of calling a function
greet("Alice"); // Output: Hello, Alice!
greet("Bob"); // Output: Hello, Bob!
Parameters and Arguments
Parameters are the variables listed inside the parentheses in the function definition. Arguments are the actual values that are sent to the function when it is called.
function add(num1, num2) { // num1 and num2 are parameters
return num1 + num2;
}
let sum = add(5, 3); // 5 and 3 are arguments
console.log(sum); // Output: 8
Return Values
The return statement is used to exit a function and return a value. If a function doesn't have a return statement, it implicitly returns undefined.
function multiply(a, b) {
return a * b; // Returns the product of a and b
}
let result = multiply(4, 6);
console.log(result); // Output: 24
function displayMessage(msg) {
console.log(msg);
// No return statement here, implicitly returns undefined
}
let output = displayMessage("Processing complete.");
console.log(output); // Output: Processing complete.
// Output: undefined
Scope of Functions
Scope refers to the accessibility (visibility) of variables. Functions create a new scope. Variables declared inside a function are local to that function and cannot be accessed from outside.
function outerFunction() {
let localVar = "I am local";
console.log(localVar); // Accessible here
function innerFunction() {
console.log(localVar); // Accessible in inner scope too
}
innerFunction();
}
outerFunction();
// console.log(localVar); // This would cause an error: localVar is not defined