LEARNING JAVASCRIPT - Trang 137

When a function is created this way, the name

g

takes priority, and to refer to the

function (from outside of the function), we use

g

; trying to access

f

will give you an

undefined variable error. Taking this into account, why would we want to do this? It

can be necessary if we want to refer to the function from within the function itself

(called recursion):

const

g

=

function

f

(

stop

) {

if

(

stop

)

console

.

log

(

'f stopped'

);

f

(

true

);

};

g

(

false

);

From inside the function, we use

f

to reference the function, and from outside we use

g

. There’s no particularly good reason to give a function two separate names, but we

do so here to make it clear how named function expressions work.
Because function declaration and function expressions look identical, you might be

wondering how JavaScript tells the two apart (or if there’s even any difference). The

answer is context: if the function declaration is used as an expression, it is a function

expression, and if it isn’t, it’s a function declaration.
The difference is mostly academic, and you don’t normally have to think about it.

When you’re defining a named function that you intend to call later, you’ll probably

use a function declaration without thinking about it, and if you need to create a func‐

tion to assign to something or pass into another function, you’ll use a function

expression.

Arrow Notation

ES6 introduces a new and welcome syntax called arrow notation (also called “fat

arrow” notation because the arrow uses an equals sign instead of a dash). It is essen‐

tially syntactic sugar (with one major functional difference we’ll get to shortly) that

reduces the number of times you have to type the word

function

, as well as the num‐

ber of curly braces you have to type.
Arrow functions allow you to simplify syntax in three ways:

• You can omit the word

function

.

• If the function takes a single argument, you can omit the parentheses.
• If the function body is a single expression, you can omit curly braces and the

return

statement.

Arrow functions are always anonymous. You can still assign them to a variable, but

you can’t create a named function like you can with the

function

keyword.

Consider the following equivalent function expressions:

Arrow Notation | 113

Liên Kết Chia Sẽ

** Đây là liên kết chia sẻ bới cộng đồng người dùng, chúng tôi không chịu trách nhiệm gì về nội dung của các thông tin này. Nếu có liên kết nào không phù hợp xin hãy báo cho admin.