Javascript functions
Created By: chatGPT
JavaScript functions are reusable blocks of code that perform a specific task. They help organize code into manageable sections and can be called whenever needed. Functions can also take input parameters and return output values.
function greet(name) {
return `Hello, ${name}!`;
}
const message = greet('Alice');
console.log(message); // Hello, Alice!
You can define a function using the function keyword followed by a name and parentheses. Within the parentheses, you can define any parameters that your function requires.
function add(a, b) {
return a + b;
}
const sum = add(5, 3);
console.log(sum); // 8
Functions can also be defined using arrow function syntax. This is a more concise way to write functions, especially for short operations.
const subtract = (x, y) => x - y;
const difference = subtract(10, 4);
console.log(difference); // 6
If you need a function without a name, you can create an anonymous function and assign it to a variable. This can be useful for callbacks or event handlers.
const multiply = function(a, b) {
return a * b;
};
const product = multiply(4, 5);
console.log(product); // 20
You can also define default parameters. These allow you to set default values for function parameters which are used if no corresponding argument is passed.
function welcome(name = 'Guest') {
return `Welcome, ${name}!`;
}
console.log(welcome()); // Welcome, Guest!
In JavaScript, functions are first-class objects. This means they can be assigned to variables, passed as arguments to other functions, and returned from functions.
function createMultiplier(factor) {
return (num) => num * factor;
}
const double = createMultiplier(2);
console.log(double(10)); // 20
Lastly, functions can be called recursively. This means a function can call itself, which can be useful for solving problems that can be broken down into smaller subproblems.
function factorial(n) {
if (n === 0) return 1;
return n * factorial(n - 1);
}
console.log(factorial(5)); // 120