Calling Functions
This document explains how to invoke or call functions in your code. Calling a function executes the code defined within that function.
Basic Function Invocation
To call a function, you use its name followed by parentheses ()
. If the function expects arguments, you provide them inside the parentheses, separated by commas.
Example: Simple Function Call
First, let's define a simple function:
function greet() {
console.log("Hello, World!");
}
Now, let's call it:
greet();
// Output: Hello, World!
Calling Functions with Arguments
Functions often take input values called arguments. These arguments are passed to the function when it's called and can be used within the function's body.
Example: Function with Arguments
function greetUser(name) {
console.log("Hello, " + name + "!");
}
greetUser("Alice"); // Output: Hello, Alice!
greetUser("Bob"); // Output: Hello, Bob!
Function Return Values
Functions can also produce a result or output value using the return
keyword. When a function returns a value, you can capture it in a variable or use it directly in expressions.
Example: Function with Return Value
function addNumbers(a, b) {
return a + b;
}
let sum = addNumbers(5, 3);
console.log(sum); // Output: 8
console.log(addNumbers(10, 20)); // Output: 30
Important:
If a function does not explicitly return a value, it implicitly returns undefined
.
Calling Methods
Methods are functions that are associated with objects. You call a method using the dot notation (.
) on the object.
Example: Object Method Call
let person = {
name: "Charlie",
sayHello: function() {
console.log("Hi, I'm " + this.name);
}
};
person.sayHello(); // Output: Hi, I'm Charlie
Parameters vs. Arguments
It's important to distinguish between parameters and arguments:
- Parameters: The names listed in the function definition.
- Arguments: The actual values passed to the function when it is called.
Tip:
Ensure that the number and types of arguments you pass when calling a function match its parameters to avoid unexpected behavior.
Understanding Function Calling Context
The context (or this
value) in which a function is called can significantly affect its behavior, especially when dealing with methods or event handlers.