Sobes.tech
Junior — Middle

Can you name and explain two main ways to declare functions in JavaScript?

sobes.tech AI

Answer from AI

In JavaScript, there are two main ways to declare functions:

  1. Function Declaration

This is the classic way, where a function is declared using the function keyword and a name:

function greet(name) {
  return `Hello, ${name}!`;
}

Such functions are hoisted to the top of their scope, so they can be called before their declaration.

  1. Function Expression

A function is created as a value and can be anonymous or named. It is usually assigned to a variable:

const greet = function(name) {
  return `Hello, ${name}!`;
};

In this case, the function is not hoisted, and can only be called after its declaration.

Arrow functions are also a type of function expression:

const greet = (name) => `Hello, ${name}!`;

They are shorter and have special behavior with the this context.

Thus, the main ways are function declaration and function expression.

Can you name and explain two main ways to declare… - sobes.tech