In JavaScript, you can define a function using the function
keyword. Here’s an example of how to define a function in JavaScript:
function addNumbers(x, y) {
return x + y;
}
In this example, we define a function called addNumbers
that takes two parameters, x
and y
, and returns their sum using the return
keyword.
Once you have defined a function in JavaScript, you can call it by referencing its name and passing any required arguments. For example:
console.log(addNumbers(2, 3)); // 5
console.log(addNumbers(10, 5)); // 15
In this example, we call the addNumbers
function twice with different arguments, and use the console.log
function to log the results to the console.
JavaScript functions can also be assigned to variables and passed as arguments to other functions, among other things. Here’s an example of how to define a function using a variable:
const multiplyNumbers = function(x, y) {
return x * y;
}
console.log(multiplyNumbers(2, 3)); // 6
console.log(multiplyNumbers(10, 5)); // 50
In this example, we define a function called multiplyNumbers
using a variable and the function expression syntax. We then call the multiplyNumbers
function twice with different arguments, and use the console.log
function to log the results to the console.
+ There are no comments
Add yours