JavaScript ยท Chapter 12 of 55
JavaScript Functions
A function is a reusable block of code designed to perform a task. You define one with the `function` keyword, and run (invoke) it by calling its name with parentheses.
Functions can accept inputs (parameters) and return an output value with the `return` keyword.
Declaring and calling
`function add(a, b) { return a + b; }` defines a function; `add(2, 3)` calls it and returns 5.
Parameters and defaults
Parameters can have default values: `function greet(name = 'Guest') {...}` uses 'Guest' if no argument is passed.
Example 1 (javascript)
function add(a, b) {
return a + b;
}
console.log(add(2, 3));Output
5A simple function that returns the sum of two numbers.
Example 2 (javascript)
function greet(name = "Guest") {
return "Hello, " + name;
}
console.log(greet());Output
Hello, GuestDefault parameters apply when no argument is given.
Key points
- Functions are defined with the `function` keyword.
- `return` sends a value back to the caller and ends execution.
- Parameters can have default values.
- Functions can be called any number of times with different arguments.
๐ก Note: A function without a return statement implicitly returns `undefined`.
