JavaScript : function declaration and expression

Started by arthyk, Oct 21, 2022, 01:48 PM

Previous topic - Next topic

arthykTopic starter

Please explain the simple difference between function representations in JavaScript: declaration and expression. That is, in what ways can functions be declared in this language? And what is the difference between these methods?


The function declaration consists of the keyword function, followed by the mandatory function name, a list of parameters in parentheses (param1, ..., paramN) and curly braces {...}, limiting the main code.

Example of a function declaration:

function isEven(num) {
  return num % 2 === 0;
isEven(24);  // => true
isEven(11);  // => false

This entry declares the isEven function, which determines whether the number is even.
The function declaration creates a variable in the current scope with an identifier equal to the function name. This variable contains a function object.

The function variable rises to the top of the current scope, which means that the function can be called before the declaration (hoisting process).
The created function is assigned a name, which means that the name property of the function object contains its name. This is useful when viewing the call stack: when debugging or reading error messages.

The function expression is defined by the keyword function, followed by an optional function name, a list of parameters in parentheses (param1, ..., paramN) and a pair of curly braces {...} that restrict the body of the code.

Examples of function expressions:

const count = function(array) { // Function expression
  return array.length;
const methods = {
  numbers: [1, 5, 8],
  sum: function() { // Function expression
return this.numbers.reduce(function(acc, num) { // Function expression
      return acc + num;
count([5, 7, 8]);  // => 3
methods.sum();  // => 14

A function expression creates a function object that can be used in various situations:

Assigning a variable as an object count = function(...) {...}
Creating a method for an object sum: function() {...}
Using a function as a callback (callback) .reduce(function(...) {...})
Function expression is a workhorse in JavaScript.
This type of function declaration is usually used, sometimes together with an arrow function (if you prefer a short syntax and lexical context).
    The following users thanked this post: Sevad