JavaScript is one of the most widely used programming languages in the world of web development. One of the fundamental building blocks of JavaScript is functions. Functions help you organize your code, provide reusability, and break down complex operations into smaller parts. Here are some examples explaining JavaScript functions:
1. Basic Function Definition:
// Simple function definition
function helloWorld() {
console.log("Hello, World!");
}
// Calling the function
helloWorld();
2. Functions with Parameters:
javascriptKopyalaDüzenle// Function definition with a parameter
function greet(name) {
console.log("Hello, " + name + "!");
}
// Calling the function and passing a parameter
greet("Ahmet");
3. Functions with Return Values:
// Function definition with a return value
function add(x, y) {
return x + y;
}
// Calling the function and using the return value
var result = add(3, 5);
console.log("Sum: " + result);
4. Function Expression:
// Defining a function as an expression
var multiply = function(x, y) {
return x * y;
};
// Calling the function and using the return value
var product = multiply(4, 6);
console.log("Product: " + product);
5. Arrow Functions (ES6):
// Arrow function definition
var divide = (x, y) => {
return x / y;
};
// Calling the arrow function and using the return value
var quotient = divide(10, 2);
console.log("Quotient: " + quotient);
JavaScript functions allow you to make your code more modular and manage operations more efficiently. These examples will help you understand basic function structures and apply them to your own projects.