To create a function in JavaScript, you can use the function
keyword, followed by the name of the function, and a set of parentheses. The code for the function goes inside curly braces:
function functionName() {
// code to be executed
}
For example:
function greet() {
console.log("Hello, world!");
}
You can then call the function by using its name followed by a set of parentheses:
greet(); // outputs "Hello, world!"
You can also define a function that takes arguments, which are values that are passed into the function when it is called. For example:
function greet(name) {
console.log(`Hello, ${name}!`);
}
greet("Alice"); // outputs "Hello, Alice!"
greet("Bob"); // outputs "Hello, Bob!"
You can define as many arguments as you like, separated by commas. The values passed in when the function is called are called “parameters.”
function greet(firstName, lastName) {
console.log(`Hello, ${firstName} ${lastName}!`);
}
greet("Alice", "Smith"); // outputs "Hello, Alice Smith!"
greet("Bob", "Jones"); // outputs "Hello, Bob Jones!"
Finally, you can use the return
keyword to specify a value that the function should return when it is called. For example:
function square(x) {
return x * x;
}
console.log(square(2)); // outputs 4
console.log(square(3)); // outputs 9