Creating Functions
One of the fundamental aspects of JavaScript is the ability to create functions. Functions allow us to encapsulate a block of code that can be reused and executed multiple times throughout our program.
To create a function in JavaScript, we use the function
keyword followed by the name of the function and a set of parentheses. Any parameters that the function takes in are listed within these parentheses. We can also define a block of code to be executed within curly braces {}
.
Here's an example of a function declaration that takes in a name
parameter and logs a greeting message to the console:
JAVASCRIPT
1function greet(name) {
2 console.log(`Hello, ${name}!`);
3}
4
5// Call the greet function
6// Output: Hello, John!
7greet('John');
xxxxxxxxxx
// Example of a function declaration
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet('John');
OUTPUT
:001 > Cmd/Ctrl-Enter to run, Cmd/Ctrl-/ to comment