How to declare and define a function in JavaScript?

In JavaScript, you can declare and define a function using the function keyword followed by the function name and parentheses. You can also specify parameters within the parentheses if the function accepts any. Here's an example:

// Function declaration function greeting() { console.log("Hello!"); } // Function definition with parameters function addNumbers(num1, num2) { return num1 + num2; }

In the above example, greeting is a function that doesn't accept any parameters and logs "Hello!" to the console. addNumbers is a function that accepts two parameters (num1 and num2) and returns their sum.

You can also assign a function to a variable, known as function expressions:

// Function expression const greeting = function() { console.log("Hello!"); }; // Function expression with arrow function syntax (ES6) const addNumbers = (num1, num2) => { return num1 + num2; };

In this case, greeting and addNumbers are variables that store anonymous functions. The function expressions are assigned to these variables using either the function keyword or the arrow function syntax (ES6).