Table of Contents
1. Function expression vs function declaration
2. Function declaration
3. Function expression
4. 总结
Home Web Front-end JS Tutorial Function expression VS function declaration in JS, let's talk about their differences

Function expression VS function declaration in JS, let's talk about their differences

Jul 01, 2021 am 10:20 AM
javascript function declaration

In JavaScript, function declarations and function expressions both use the function keyword to create functions. Do you think they are very similar and can be easily confused? The following article will take you to analyze function expressions and function declarations, and introduce the differences between function expressions and function declarations.

Function expression VS function declaration in JS, let's talk about their differences

In JavaScript, the function keyword can do a simple job: create a function. However, using keywords to define functions allows you to create functions with different properties.

In this article, let's take a look at how to use the function keyword to define function declarations and function expressions, and what are the differences between the two functions.

1. Function expression vs function declaration

Function declaration and function expression are 2 ways to create a function using the function keyword.

As an example to illustrate the difference, we create two versions of the sums function:

function sumA(a, b) {
  return a + b;
}

(function sumB(a, b) {
  return a + b;
});

sumA(1, 2); // ???
sumB(1, 2); // ???
Copy after login

Try it yourself: https://jsfiddle.net/dmitri_pavlutin/8b46yokr/2/

In general, define the function as usual (sumA function). In the other case, the function is placed within a pair of parentheses (sumBfunction).

What happens if we call sumA(1,2) and sumB(1,2)?

As expected, sumA(1, 2) returns 3. However, calling sumB(1, 2) throws an exception: Uncaught ReferenceError: sumB is not defined.

The reason for this is that sumA is created using a function declaration that creates a function variable (with the same name as the function name) in the current scope. But sumB is created using a function expression (wrap it in parentheses) which does not create a function variable in the current scope.

If you want to access a function created using a function expression, then save the function object to a variable:

// Works!
const sum = (function sumB(a, b) {
  return a + b;
});

sum(1, 2); // => 3
Copy after login

If the statement begins with the `function` keyword , it is a function declaration, otherwise it is a function expression.

// 函数声明:以`function`关键字开头
function sumA(a, b) {
  return a + b;
}

// 函数表达式:不以`function`关键字开头
const mySum = (function sumB(a, b) {
  return a + b;
});

// 函数表达式:不以`function`关键字开头
[1, 2, 3].reduce(function sum3(acc, number) { 
  return acc + number 
});
Copy after login

From a high-level perspective, function declarations are useful for creating standalone functions, but function expressions can be used as callbacks.

Now, let's take a closer look at the behavior of function declarations and function expressions.

2. Function declaration

As you have seen in the previous example, sumA is a function declaration:

// Function declaration
function sumA(a, b) {
  return a + b;
}

sumA(4, 5); // => 9
Copy after login

When a statement contains the function keyword, followed by the function name, a pair of parentheses (param1, param2, paramN) and a pair of curly braces {} Function declaration occurs when the function body in .

A function declaration creates a function variable: a variable with the same name as the function name (for example, sumA in the previous example). The function variable can be accessed in the current scope (before and after the function declaration), and even within the function scope itself.

Function variables are usually used to call functions or pass function objects to other functions (passing to higher-order functions).

For example, write a function sumArray(array) that recursively accumulates the items of an array (the array can contain numbers or other arrays):

sumArray([10, [1, [5]]]); // => 16

function sumArray(array) {
  let sum = 0;
  for (const item of array) {
    sum += Array.isArray(item) ? sumArray(item) : item;
  }
  return sum;
}

sumArray([1, [4, 6]]); // => 11
Copy after login

Try it yourself: https://jsfiddle.net/dmitri_pavlutin/n7wcryuo/

function sumArray(array) { ... } is a function declaration.

Function variables containing function objects sumArrayAvailable in the current scope: sumArray([10, [1, [5]]])before and sumArray([1, [4, 6]])After the function declaration, and the scope of the function itselfsumArray([1, [4, 6]]) (recursive calls are allowed) .

Due to hoisting, function variables are available before the function is declared.

2.1 Notes on function declaration

The function declaration syntax is to create independent functions. Function declarations should be in the global scope, or directly in the scope of other functions:

// Good!
function myFunc1(param1, param2) {
  return param1 + param2;
}

function bigFunction(param) {
  // Good!
  function myFunc2(param1, param2) {
    return param1 + param2;
  }

  const result = myFunc2(1, 3);
  return result + param;
}
Copy after login

For the same reason, it is not recommended to declare conditions (if) and loops (while, for) using function declarations:

// Bad!
if (myCondition) {
  function myFunction(a, b) {
    return a * b;
  }
} else {
  function myFunction(a, b) {
    return a + b;
  }
}

myFunction(2, 3);
Copy after login

Use function expressions for better execution of conditionally created functions.

3. Function expression

When the function keyword creates a function (with or without a name) inside an expression, The function expression will appear.

The following is an example of a function created using an expression:

// Function expressions

const sum = (function sumB(a, b) {
  return a + b;
});

const myObject = {
  myMethod: function() {
    return 42;
  }
};

const numbers = [4, 1, 6];
numbers.forEach(function callback(number) {
  console.log(number);
  // logs 4
  // logs 1
  // logs 1
});
Copy after login

Two types of functions are created in a function expression:

  • If the function in the expression Without a name, like function(){return 42}, that's an anonymous function expression
  • If the function has a name, like sumB in the previous example and callback, then this is a named function expression

3.1 Notes on function expressions

Function expressions are suitable for callbacks or functions created as conditions:

// Functions created conditionally
let callback;
if (true) {
  callback = function() { return 42 };
} else {
  callback = function() { return 3.14 };
}

// Functions used as callbacks
[1, 2, 3].map(function increment(number) {
  return number + 1;
}); // => [2, 3, 4]
Copy after login

If you have created a named function expression, please note that the function variable is only available within the scope of the created function:

const numbers = [4];
numbers.forEach(function callback(number) {
  console.log(callback); // logs function() { ... }
});

console.log(callback); // ReferenceError: callback is not defined
Copy after login

试一试:https://jsfiddle.net/dmitri_pavlutin/sujwmp10/2/

callback是一个命名的函数表达式,因此callback函数变量仅在callback()函数使用域可用,而在外部则不可用。

但是,如果将函数对象存储到常规变量中,则可以在函数作用域内外从该变量访问函数对象:

const callback = function(number) {
  console.log(callback); // logs function() { ... }
};

const numbers = [4];
numbers.forEach(callback);
console.log(callback); // logs function() { ... }
Copy after login

试一试:https://jsfiddle.net/dmitri_pavlutin/1btmrcu2/1/

4. 总结

根据使用function关键字创建函数的方式,可以通过两种方法来创建函数:函数声明和函数表达式。

留个问题: function sum(a, b) { return a + b } + 1 是函数声明还是函数表达式,可以在留言中说出你的答案。

英文文章地址:https://dmitripavlutin.com/javascript-function-expressions-and-declarations/

作者:Dmitri Pavlutin

更多编程相关知识,请访问:编程视频!!

The above is the detailed content of Function expression VS function declaration in JS, let's talk about their differences. For more information, please follow other related articles on the PHP Chinese website!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Default parameters in C++ function declarations: a comprehensive analysis of their declaration and usage Default parameters in C++ function declarations: a comprehensive analysis of their declaration and usage May 02, 2024 pm 03:09 PM

Default parameters in C++ provide the ability to specify default values ​​for function parameters, thereby enhancing code readability, simplicity, and flexibility. Declare default parameters: Add the "=" symbol after the parameter in the function declaration, followed by the default value. Usage: When the function is called, if optional parameters are not provided, the default values ​​will be used. Practical case: A function that calculates the sum of two numbers. One parameter is required and the other is optional and has a default value of 0. Advantages: Enhanced readability, increased flexibility, reduced boilerplate code. Note: It can only be specified in the declaration, it must be at the end, and the types must be compatible.

How to implement an online speech recognition system using WebSocket and JavaScript How to implement an online speech recognition system using WebSocket and JavaScript Dec 17, 2023 pm 02:54 PM

How to use WebSocket and JavaScript to implement an online speech recognition system Introduction: With the continuous development of technology, speech recognition technology has become an important part of the field of artificial intelligence. The online speech recognition system based on WebSocket and JavaScript has the characteristics of low latency, real-time and cross-platform, and has become a widely used solution. This article will introduce how to use WebSocket and JavaScript to implement an online speech recognition system.

WebSocket and JavaScript: key technologies for implementing real-time monitoring systems WebSocket and JavaScript: key technologies for implementing real-time monitoring systems Dec 17, 2023 pm 05:30 PM

WebSocket and JavaScript: Key technologies for realizing real-time monitoring systems Introduction: With the rapid development of Internet technology, real-time monitoring systems have been widely used in various fields. One of the key technologies to achieve real-time monitoring is the combination of WebSocket and JavaScript. This article will introduce the application of WebSocket and JavaScript in real-time monitoring systems, give code examples, and explain their implementation principles in detail. 1. WebSocket technology

How to use JavaScript and WebSocket to implement a real-time online ordering system How to use JavaScript and WebSocket to implement a real-time online ordering system Dec 17, 2023 pm 12:09 PM

Introduction to how to use JavaScript and WebSocket to implement a real-time online ordering system: With the popularity of the Internet and the advancement of technology, more and more restaurants have begun to provide online ordering services. In order to implement a real-time online ordering system, we can use JavaScript and WebSocket technology. WebSocket is a full-duplex communication protocol based on the TCP protocol, which can realize real-time two-way communication between the client and the server. In the real-time online ordering system, when the user selects dishes and places an order

What impact does the order of declaration and definition of C++ functions have? What impact does the order of declaration and definition of C++ functions have? Apr 19, 2024 pm 01:42 PM

In C++, the order of function declarations and definitions affects the compilation and linking process. The most common is that the declaration comes first and the definition comes after; you can also use "forwarddeclaration" to place the definition before the declaration; if both exist at the same time, the compiler will ignore the declaration and only use the definition.

How to implement an online reservation system using WebSocket and JavaScript How to implement an online reservation system using WebSocket and JavaScript Dec 17, 2023 am 09:39 AM

How to use WebSocket and JavaScript to implement an online reservation system. In today's digital era, more and more businesses and services need to provide online reservation functions. It is crucial to implement an efficient and real-time online reservation system. This article will introduce how to use WebSocket and JavaScript to implement an online reservation system, and provide specific code examples. 1. What is WebSocket? WebSocket is a full-duplex method on a single TCP connection.

JavaScript and WebSocket: Building an efficient real-time weather forecasting system JavaScript and WebSocket: Building an efficient real-time weather forecasting system Dec 17, 2023 pm 05:13 PM

JavaScript and WebSocket: Building an efficient real-time weather forecast system Introduction: Today, the accuracy of weather forecasts is of great significance to daily life and decision-making. As technology develops, we can provide more accurate and reliable weather forecasts by obtaining weather data in real time. In this article, we will learn how to use JavaScript and WebSocket technology to build an efficient real-time weather forecast system. This article will demonstrate the implementation process through specific code examples. We

Simple JavaScript Tutorial: How to Get HTTP Status Code Simple JavaScript Tutorial: How to Get HTTP Status Code Jan 05, 2024 pm 06:08 PM

JavaScript tutorial: How to get HTTP status code, specific code examples are required. Preface: In web development, data interaction with the server is often involved. When communicating with the server, we often need to obtain the returned HTTP status code to determine whether the operation is successful, and perform corresponding processing based on different status codes. This article will teach you how to use JavaScript to obtain HTTP status codes and provide some practical code examples. Using XMLHttpRequest

See all articles