create function in javascript

Creating a function in JavaScript is essential for code reusability and organization. Here is the basic syntax for a JavaScript function:

index.tsx
function functionName(parameter1, parameter2) {
  // function logic
  return result;
}
87 chars
5 lines

Let's break it down:

  • function keyword: This is used to indicate that we are creating a function.
  • functionName: This is the name of the function you want to create. Choose a name that best describes what the function does.
  • (parameter1, parameter2): These are optional parameters that the function takes in. You can have zero or multiple parameters separated by commas.
  • { // function logic }: This is where you write the code that you want the function to perform.
  • return: This keyword is used to give the result back to the caller once the function is executed. You can return any value or object, including an array.
  • If you don't specify a return statement, the function will return undefined by default.

Here is an example of how to create a function in JavaScript:

index.tsx
function addNumbers(num1, num2) {
  return num1 + num2;
}

// call the function
const sum = addNumbers(3, 5);
console.log(sum); // output: 8
141 chars
8 lines

In this example, we create a function called addNumbers that takes in two parameters num1 and num2. The function adds them together and returns the result. We then call the function and pass in the values 3 and 5. Finally, we log the value of sum to the console which outputs 8.

gistlibby LogSnag