Chapter 5_ Functions in JavaScript
Chapter 5_ Functions in JavaScript
By Ahmed Thaer
What is a Function?
When I first started coding, my programs got messy quickly. I found myself copying and pasting
the same lines over and over. That’s when I discovered functions. Think of a function as a
mini-program inside your main program: it performs a specific task, and you can “call” (run) it
whenever you need that task done.
● Maintainability: Fix bugs in one spot, not everywhere you used the code.
There are several ways to define a function in JavaScript, but here’s the most common:
javascript
CopyEdit
function greet() {
console.log('Hello, world!');
}
To run (“call”) this function, just use its name with parentheses:
javascript
CopyEdit
greet(); // Output: Hello, world!
Function Parameters and Arguments
javascript
CopyEdit
function greet(name) {
console.log('Hello, ' + name + '!');
}
● Argument: The actual value you send in when you call the function ('Ahmed').
Return Values
A function can give back (return) a result, which you can use elsewhere in your code.
javascript
CopyEdit
function add(a, b) {
return a + b;
}
Function Expression
javascript
CopyEdit
const sayHi = function() {
console.log('Hi!');
};
sayHi();
javascript
CopyEdit
const multiply = (a, b) => {
return a * b;
};
console.log(multiply(3, 4)); // Output: 12
javascript
CopyEdit
const square = x => x * x;
console.log(square(5)); // Output: 25
Default Parameters
javascript
CopyEdit
function greet(name = 'friend') {
console.log('Hello, ' + name + '!');
}
greet(); // Output: Hello, friend!
Variables declared inside a function only exist in that function. This is called local scope.
javascript
CopyEdit
function showSecret() {
let secret = 'Hidden!';
console.log(secret); // Works here
}
showSecret();
// console.log(secret); // Error! Not defined outside the function
Variables declared outside any function are global and can be used anywhere.
Quick Practice
1. Write a function that multiplies two numbers and returns the result.
2. Create a function that takes a name as input and returns “Good morning, [name]!”
Summary
Next up: Objects and Arrays—the main way we organize and manage lots of data in
JavaScript!