js function in javascript

To define a JavaScript function, you can use the function keyword followed by the name of the function and a pair of parentheses. Inside the parentheses, you can define any parameters that the function may accept. The function body is enclosed in curly braces {}.

Here is an example of a simple JavaScript function that takes two numbers as parameters and returns their sum:

index.tsx
function addNumbers(num1, num2) {
  return num1 + num2;
}
58 chars
4 lines

To call the function and use its result, you can simply use its name followed by parentheses with the arguments you want to pass in. For example:

index.tsx
let result = addNumbers(5, 3); // The result variable will hold the value 8
console.log(result); // Output: 8
110 chars
3 lines

You can also assign a function to a variable, which is known as a function expression. Here is an example:

index.tsx
const multiplyNumbers = function(num1, num2) {
  return num1 * num2;
};

let result = multiplyNumbers(5, 3); // The result variable will hold the value 15
console.log(result); // Output: 15
190 chars
7 lines

Additionally, you can use arrow functions, which provide a concise syntax for writing functions. Here is an example of an arrow function:

index.tsx
const divideNumbers = (num1, num2) => {
  return num1 / num2;
};

let result = divideNumbers(10, 2); // The result variable will hold the value 5
console.log(result); // Output: 5
180 chars
7 lines

These are the basic ways to define and use functions in JavaScript. Functions are a fundamental concept in JavaScript programming and are used to encapsulate reusable blocks of code.

related categories

gistlibby LogSnag