In JavaScript, a function can be defined in several ways:

Using the function keyword:

function myFunction() {
    // code to be executed

Using function expressions:

var myFunction = function() {
    // code to be executed

Using arrow function (ES6+):

let myFunction = () => {
    // code to be executed

All of the above examples define a function named myFunction. The function can be called by using its name followed by parentheses (). For example:


You can also pass parameters to a function, for example:

function add(a, b) {
  return a + b;
console.log(add(2,3)); //5

And you can also define function with default parameter:

function greet(name='User') {
  return `Hello ${name}`;
console.log(greet()); //Hello User
console.log(greet('John')); //Hello John

You can use any of the above methods to define a function in JavaScript.

Also Read:

Categorized in: