Module 5: Functions
Declaring and Calling Functions
Functions are fundamental building blocks in JavaScript. They are reusable blocks of code that perform a specific task.
Declaring a Function (Function Declaration):
Uses the function
keyword, followed by the function name, parentheses ()
for parameters, and curly braces {}
for the function body.
function greet() { console.log("Hello there!"); }
Calling a Function: To execute a function, you "call" or "invoke" it by its name followed by parentheses.
greet(); // Output: Hello there!
Function Parameters and Arguments:
- Parameters: Variables listed in the function definition (inside the parentheses). They act as placeholders for values that will be passed to the function.
- Arguments: The actual values passed to the function when it is called.
function sayHelloTo(name) { // 'name' is a parameter console.log("Hello, " + name + "!"); } sayHelloTo("Alice"); // "Alice" is an argument. Output: Hello, Alice! sayHelloTo("Bob"); // "Bob" is an argument. Output: Hello, Bob!
The return
Statement:
Functions can return a value back to the caller using the return
statement. If a function doesn't have a return
statement, or has a return
statement without a value, it implicitly returns undefined
.
function add(num1, num2) { return num1 + num2; // Returns the sum } let sum = add(5, 3); console.log(sum); // Output: 8 function doNothing() { // No return statement } let result = doNothing(); console.log(result); // Output: undefined
Once a return
statement is executed, the function immediately stops executing.