JavaScript Functions
Functions in JavaScript are reusable blocks of code that can be called multiple times with different arguments. Functions allow you to encapsulate logic in a single unit and make your code more organized and readable.
Here is an example of a simple function in JavaScript:
function greet(name) {
console.log("Hello " + name + "!");
}
greet("John"); // Hello John!
greet("Jane"); // Hello Jane!
In the example, the function greet
takes a single argument name
and logs a greeting to the console. The function can be called multiple times with different values for name
, allowing you to reuse the same logic in multiple places.
Functions can also return a value. The return
keyword is used to specify the value that a function should return.
Here is an example of a function that returns a value:
function square(x) {
return x * x;
}
let result = square(5);
console.log(result); // 25
In the example, the function square
takes a single argument x
and returns the square of x
. The value returned by the function is assigned to the variable result
and logged to the console.
Functions are a fundamental aspect of JavaScript and are used to encapsulate logic, make code more modular and readable, and allow for code reuse.
Leave a Comment