JavaScript Functions Basics:
JavaScript Functions
JavaScript functions are blocks of code that can be defined and invoked (called) multiple times throughout your code. Functions can accept input parameters and return output values. Functions are an essential part of JavaScript, and are used to perform specific tasks and reduce code repetition.
Here's an example of a basic function in JavaScript:
javascript
function sayHello() {
console.log("Hello, World!");
}
Output: Hello, World!
In this example, the sayHello() function simply logs a message to the console. You can call the function by using its name, followed by parentheses.
Functions can also accept parameters, which allow you to pass data to the function. Here's an example:
javascript
function greet(name) {
console.log("Hello, " + name + "!");
}
Output: Hello, Alice!
Output: Hello, Bob!
In this example, the greet() function accepts a name parameter, which is used to construct a personalized greeting. When you call the function, you pass in the name as an argument.
Functions can also return values, which allow you to use the result of the function in other parts of your code. Here's an example:
javascript
function square(num) {
return num * num;
}
let result = square(5);
Output: 25
In this example, the square() function accepts a num parameter and returns the square of that number. When you call the function, you store the result in a variable and then log it to the console.
Functions are a powerful tool in JavaScript that allow you to write reusable code and make your code more modular and easier to read.