function keyword followed by a name and a set of parentheses, which can optionally contain one or more parameters. The function body is then enclosed in curly braces. Here is an example of a basic function that takes two parameters and returns their sum:
javascript
function addNumbers(num1, num2) { return num1 + num2; }
Once a function is defined, it can be called by its name followed by a set of parentheses containing any necessary arguments. Here is an example of calling the addNumbers function with the arguments 2 and 3:
javascript
let sum = addNumbers(2, 3); console.log(sum); // Outputs 5
In addition to regular functions, JavaScript also supports anonymous functions (also known as lambda functions) which can be defined without a name and assigned to a variable. Here is an example of an anonymous function that takes a single parameter and returns its square:
javascript
let square = function(num) { return num * num; }; let result = square(5); console.log(result); // Outputs 25
JavaScript also supports arrow functions, which provide a more concise syntax for defining anonymous functions. Here is an example of an arrow function that takes a single parameter and returns its square:
javascript
let square = (num) => num * num; let result = square(5); console.log(result); // Outputs 25


0 Comments