Javascript regular functions
Created By: chatGPT
In JavaScript, functions are one of the fundamental building blocks. A regular function can be declared using the
function
keyword, followed by the name of the function and parentheses. Here's how you can define a simple function that takes parameters and returns a value:function add(a, b) {
return a + b;
}
const result = add(5, 3); // result is 8
You can define functions that do not take any parameters as well. If you don't need to pass any values into your function, you can leave the parentheses empty:
function greet() {
console.log('Hello, world!');
}
greet(); // Prints 'Hello, world!'
Functions can also be assigned to variables, which allows for a more flexible declaration. This is called a function expression. For instance:
const multiply = function(x, y) {
return x * y;
};
const product = multiply(4, 5); // product is 20
You can define functions that accept an arbitrary number of arguments by using the
arguments
object. This allows your function to handle any number of inputs. Here's an example:function sumAll() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
const totalSum = sumAll(1, 2, 3, 4, 5); // totalSum is 15
Lastly, you can declare functions to be immediately invoked by wrapping the function in parentheses and adding another pair of parentheses at the end. This can be useful for executing code immediately:
(function() {
console.log('This function runs immediately!');
})();