惯性聚合 高效追踪和阅读你感兴趣的博客、新闻、科技资讯
阅读原文 在惯性聚合中打开

推荐订阅源

Cisco Talos Blog
Cisco Talos Blog
freeCodeCamp Programming Tutorials: Python, JavaScript, Git & More
爱范儿
爱范儿
奇客Solidot–传递最新科技情报
奇客Solidot–传递最新科技情报
Jina AI
Jina AI
雷峰网
雷峰网
The Register - Security
The Register - Security
The Cloudflare Blog
博客园 - 【当耐特】
M
MIT News - Artificial intelligence
I
InfoQ
博客园 - 三生石上(FineUI控件)
H
Help Net Security
博客园 - 司徒正美
Vercel News
Vercel News
WordPress大学
WordPress大学
S
SegmentFault 最新的问题
云风的 BLOG
云风的 BLOG
B
Blog
Google DeepMind News
Google DeepMind News
B
Blog RSS Feed
L
LangChain Blog
人人都是产品经理
人人都是产品经理
GbyAI
GbyAI
T
The Blog of Author Tim Ferriss
T
Tailwind CSS Blog
aimingoo的专栏
aimingoo的专栏
让小产品的独立变现更简单 - ezindie.com
让小产品的独立变现更简单 - ezindie.com
Recorded Future
Recorded Future
小众软件
小众软件
Martin Fowler
Martin Fowler
罗磊的独立博客
Stack Overflow Blog
Stack Overflow Blog
钛媒体:引领未来商业与生活新知
钛媒体:引领未来商业与生活新知
酷 壳 – CoolShell
酷 壳 – CoolShell
腾讯CDC
CTFtime.org: upcoming CTF events
CTFtime.org: upcoming CTF events
Apple Machine Learning Research
Apple Machine Learning Research
Cyber Security Advisories - MS-ISAC
Cyber Security Advisories - MS-ISAC
博客园 - Franky
Hugging Face - Blog
Hugging Face - Blog
Y
Y Combinator Blog
V
Visual Studio Blog
F
Fortinet All Blogs
Microsoft Azure Blog
Microsoft Azure Blog
大猫的无限游戏
大猫的无限游戏
Engineering at Meta
Engineering at Meta
N
Netflix TechBlog - Medium
V
V2EX
Blog — PlanetScale
Blog — PlanetScale

Dmitri Pavlutin Blog

Pure Functions in JavaScript: A Beginner's Guide Record Type in TypeScript: A Quick Intro How to Write Comments in React: The Good, the Bad and the Ugly 4 Ways to Create an Enum in JavaScript React forwardRef(): How to Pass Refs to Child Components TypeScript Function Types: A Beginner's Guide How to Use v-model to Access Input Values in Vue Mastering Vue refs: From Zero to Hero Environment Variables in JavaScript: process.env 5 Must-Know Differences Between ref() and reactive() in Vue How to Destructure Props in Vue (Composition API) Triangulation in Test-Driven Development How to Use nextTick() in Vue Programming to Interface Vs to Implementation A Smarter JavaScript Mapper: array.flatMap() Array Grouping in JavaScript: Object.groupBy() How to Access ES Module Metadata using import.meta JSON Modules in JavaScript How to Trim Strings in JavaScript TypeScript Function Overloading How to Debounce and Throttle Callbacks in Vue How to Show/Hide Elements in Vue Sparse vs Dense Arrays in JavaScript How to Fill an Array with Initial Values in JavaScript Covariance and Contravariance in TypeScript What are Higher-Order Functions in JavaScript? How to Use TypeScript with React Components Index Signatures in TypeScript How to Use React useReducer() Hook unknown vs any in TypeScript A Guide to React Context and useContext() Hook How to Use Promise.any() 2 Ways to Remove a Property from an Object in JavaScript 'return await promise' vs 'return promise' in JavaScript How to Use Promise.allSettled() How to Use fetch() with JSON JavaScript Promises: then(f,f) vs then(f).catch(f) What is a Promise in JavaScript? How to Use Promise.all() A Simple Guide to Component Props in React Don't Stop Me Now: How to Use React useTransition() hook A Simple Explanation of JavaScript Variables: const, let, var ES Modules Dynamic Import How to Memoize with React.useMemo() How to Cleanup Async Effects in React Why Math.max() Without Arguments Returns -Infinity How to Debounce and Throttle Callbacks in React How to Use ES Modules in Node.js Solving a Mystery Behavior of parseInt() in JavaScript How to Use Array Reduce Method in JavaScript 3 Ways to Merge Arrays in JavaScript A Guide to Jotai: the Minimalist React State Management Library The Difference Between Values and References in JavaScript How to Implement a Queue in JavaScript A Helpful Algorithm to Determine "this" value in JavaScript React useRef() Hook Explained in 3 Steps 7 Interview Questions on "this" keyword in JavaScript. Can You Answer Them? How to Greatly Enhance fetch() with the Decorator Pattern 7 Interview Questions on JavaScript Closures. Can You Answer Them? What's a Method in JavaScript? array.sort() Does Not Simply Sort Numbers in JavaScript How to Solve the Infinite Loop of React.useEffect() The New Array Method You'll Enjoy: array.at(index) What's the Difference between DOM Node and Element? Why Promises Are Faster Than setTimeout()? Everything About Callback Functions in JavaScript How React Updates State 5 Mistakes to Avoid When Using React Hooks 5 Best Practices to Write Quality JavaScript Variables Type checking in JavaScript: typeof and instanceof operators 3 Ways to Check if a Variable is Defined in JavaScript React Forms Tutorial: Access Input Values, Validate, Submit Forms Prototypal Inheritance in JavaScript How to Timeout a fetch() Request How to Learn JavaScript If You're a Beginner A Simple Explanation of React.useEffect() A Simple Explanation of JavaScript Iterators How to Use React Controlled Inputs Everything about null in JavaScript How to Use Fetch with async/await Getting Started with Arrow Functions in JavaScript An Interesting Explanation of async/await in JavaScript Front-end Architecture: Stable and Volatile Dependencies Is it Safe to Compare JavaScript Strings? How to Access Object's Keys, Values, and Entries in JavaScript What Actually is a String in JavaScript? 3 Ways to Shallow Clone Objects in JavaScript (w/ bonuses) Checking if an Array Contains a Value in JavaScript JavaScript Event Delegation: A Beginner's Guide How to Parse URL in JavaScript: hostname, pathname, query, hash 3 Ways to Detect an Array in JavaScript How to Get the Screen, Window, and Web Page Sizes in JavaScript 3 Ways to Check If an Object Has a Property/Key in JavaScript How to Compare Objects in JavaScript Object.is() vs Strict Equality Operator in JavaScript Own and Inherited Properties in JavaScript 5 Differences Between Arrow and Regular Functions How to Use Object Destructuring in JavaScript Your Guide to React.useCallback() 5 JavaScript Scope Gotchas
Don't Confuse Function Expressions and Function Declarations in JavaScript
Dmitri Pavlutin · 2021-05-04 · via Dmitri Pavlutin Blog

In JavaScript, the function keyword does a simple job: creates a function. However, the way you define a function using the keyword can create functions with different properties.

In this post, you'll find how using the function keyword you can write function declarations and function expressions, and what are the differences between the 2 types of functions.

Table of Contents

  • 1. Function expressions vs function declarations
  • 2. The function declaration
    • 2.1 Dos and don'ts of the function declaration
  • 3. The function expression
    • 3.1 Dos and don'ts of the function expression
  • 4. Summary

1. Function expressions vs function declarations

Function declarations and function expressions are 2 ways to create functions using the function keyword.

Let's pick an example to demonstrate the difference — let's create 2 versions of a function that sums numbers:


function sumA(a, b) {

return a + b;

}

(function sumB(a, b) {

return a + b;

});

sumA(1, 2); // ???

sumB(1, 2); // ???


Open the demo.

In one case, you define the function as usual (the sumA function). In the other case, the function is placed into a pair of parentheses (the sumB function).

What would happen if you invoke sumA(1, 2) and sumB(1, 2)?

As expected, sumA(1, 2) simply returns the sum of 1 and 2 numbers — 3. However, invoking sumB(1, 2) throws an error Uncaught ReferenceError: sumB is not defined.

The explanation is that sumA was created using a function declaration, which creates a function variable (with the same name as the function name) in the current scope. But sumB was created using a function expression (it is wrapped into parentheses), which doesn't create a function variable in the current scope.

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


// Works!

const sum = (function sumB(a, b) {

return a + b;

});

sum(1, 2); // => 3


Here's a simple hint on how to distinguish a function declaration from a function expression:

If the statement starts with the function keyword, then it's a function declaration, otherwise it's a function expression.


// Function declaration: STARTS with `function` keyword

function sumA(a, b) {

return a + b;

}

// Function expression: DOES NOT START with `function` keyword

const mySum = (function sumB(a, b) {

return a + b;

});

// Function expression: DOES NOT START with `function` keyword

[1, 2, 3].reduce(function sum3(acc, number) {

return acc + number

});


From a higher point of view, function declarations are useful to create standalone functions, but function expressions are good as callbacks.

Now, let's dive more into the behavior of the function declarations and function expressions.

2. The function declaration

As you already saw in the previous example, sumA is a function declaration:


// Function declaration

function sumA(a, b) {

return a + b;

}

sumA(4, 5); // => 9


A function declaration occurs when a statement contains the function keyword followed by the function name, a pair of parentheses with the parameters (param1, param2, paramN), and the function body enclosed into a pair of curly braces { }.

The function declaration creates a function variable — a variable with the same name as the function name (e.g. sumA from the previous example). The function variable is accessible in the current scope (before and after the function declaration) and even inside the function's scope itself.

The function variable is normally used to invoke the function or pass around the function object to other functions (to higher-order functions).

For example, let's write a function sumArray(array) that sums recursively items of an array (the array can contain either 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


Open the demo.

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

The function variable sumArray, containing the function object, is available in the current scope: before sumArray([10, [1, [5]]]) and after sumArray([1, [4, 6]]) the function declaration, and also in the scope of the function itself sumArray(item) (allowing recursive calls).

The function variable is available before the function declaration thanks to hoisting.

2.1 Dos and don'ts of the function declaration

The role of the function declaration syntax is to create standalone functions. Function declarations are expected inside the global scope or the direct 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;

}


Using the same reason it is not recommended to use function declarations inside conditionals (if) and loops (while, for):


// Bad!

if (myCondition) {

function myFunction(a, b) {

return a * b;

}

} else {

function myFunction(a, b) {

return a + b;

}

}

myFunction(2, 3);


Creating functions conditionally is better performed using function expressions.

3. The function expression

The function expression occurs when the function keyword creates a function (with or without a name) inside of an expression.

The following are examples of functions created using expressions:


// 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

});


There are 2 kinds of functions created inside a function expression:

  • If the function inside the expression doesn't have a name, e.g. function() { return 42 }, then that's an anonymous function expression
  • If the function has a name, e.g. sumB and callback in the previous example, then that's a named function expression

3.1 Dos and don'ts of the function expression

Function expressions fit good as callbacks or functions created by condition:


// 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]


If you've created a named function expression, note that the function variable is available only inside the created function scope:


const numbers = [4];

numbers.forEach(function callback(number) {

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

});

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


Open the demo.

callback is a named function expression, thus the callback function variable is available only inside the callback() function scope, but not outside.

However, if you store the function object into a regular variable, then you can access the function object from that variable inside and outside of the function scope:


const callback = function(number) {

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

};

const numbers = [4];

numbers.forEach(callback);

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


Open the demo.

4. Summary

Depending on how you use the function keyword to create functions, you can end in 2 ways to create function: function declaration and function expression.

A function declaration happens when you start the statement with the function keyword:


// Function declaration

function sumA(a, b) {

return a + b;

}


Function declarations are useful to create standalone, general purpose, functions.

However, if a statement doesn't start with function keyword, then you have a function expression:


// Function expression

(function sumB(a, b) {

return a + b;

});


The functions created using functions expressions are useful to create callbacks or functions by condition.

Challenge: is function sum(a, b) { return a + b } + 1; a function declaration or function expression? Write your explanation in a comment below!