Lesson 11 - Functions in JavaScript
A function in programming is a "named" block of code that can be used whenever needed. Any time you need the same logic that exists within that block of code(the function), you just call it's name. Sometimes, you call the name and you also pass it some information(in brackets right next to the name) it needs to run its logic.
This concept is super useful because it allows to avoid repeting a whole/part of a code and therefore reduces the size of our code base. So you endup with an-easy-to-maintain code base.
Let's see how that is done in JavaScript.
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Patricia");
greet("Alima");
Explanation:
- A function is a reusable block of code that performs a specific task.
function greet(name) { ... }
defines a function namedgreet
that takesname
as a parameter.- When we call
greet("Patricia")
, it outputs "Hello, Patricia!". - Functions help avoid repetition and make code easier to manage.
Try your hand:
1. Create a File:
Create a new file named lesson11-functions.html
.
2. Write the Code:
Copy and paste the following code into your file:
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Lesson 11 - Functions</title>
</head>
<body>
<script>
function greet(name) {
console.log("Hello, " + name + "!");
}
greet("Alice");
greet("Bob");
</script>
</body>
</html>
Save your file
3. Preview the File:
- Open the file in your browser and access the developer console.
- Observe the output:
Hello, Alice!
Hello, Bob!
4. Experiment:
- Change "Alice" and "Bob" to your name or any other name.
- Modify the function to
return
the greeting instead of logging it:
function greet(name) {
return "Hello, " + name + "!";
}
let message = greet("Charlie");
console.log(message);
- Try calling greet() without a name and see what happens.