JavaScript - 5
JavaScript - 5: Functions
Functions let you group instructions together so you can run the same code whenever you need it.
Instead of writing the same greeting again and again, you can create one function and give it different names to work with.
Your challenge: Create a function called greet that accepts a name, prints a greeting, and then call it with a name of your choice.
What is a function?
A function is a reusable block of code.
You define the function once, then call it whenever you want those instructions to run.
For example: function greet() { console.log("Hello!"); }
Creating the function does not automatically run it. You still need to call it: greet();
What is a parameter?
A parameter is a name used by the function to receive a value.
In: function greet(name) the word name is the parameter.
Inside the function, you can use that parameter just like another variable.
For example: console.log(`Hello, ${name}!`);
What happens when you call the function?
If you write: greet("Maya");
the value "Maya" is passed into the function. While that function call is running, name contains "Maya".
The output becomes: Hello, Maya!
Call the same function again:
One of the most useful things about functions is that the same instructions can work with different values.
Try: greet("Maya");greet("Jordan");greet("Sam");
The function stays the same, but each call produces a different greeting.
Parameter vs. argument
These two words sound similar but describe different parts of the function.
In: function greet(name) name is a parameter.
In: greet("Maya") "Maya" is an argument.
The parameter is the placeholder in the function definition. The argument is the actual value you provide when calling it.
Try two parameters:
Functions can receive more than one value.
For example: function introduce(name, hobby)
You could then print: `Hi, I'm ${name} and I enjoy ${hobby}.`
And call it with: introduce("Maya", "drawing");
Experiment: Change the greeting inside the function without changing any of the function calls.
Every call should now use the updated message. This is one of the main reasons functions are useful: one change can update behavior in several places.
Good JavaScript habit: Give functions names that describe what they do. Names such as greet, calculateTotal, or showMessage are easier to understand than vague names such as doThing.
👀 Show Solution
function greet(name) {
console.log(`Hello, ${name}! Welcome to JavaScript.`);
}
greet("Maya");The function is defined with one parameter called name. When greet("Maya") runs, the argument "Maya" becomes the value of that parameter.
You can call the same function again with a different name without rewriting the greeting logic.
