JavaScript Course

Ngôn ngữ tương tác cho Web

Bài học: functions-comprehensive

JavaScript Course Content

JavaScript Functions - Comprehensive Guide

Master JavaScript functions from basics to advanced concepts including closures, higher-order functions, async/await, and functional programming patterns.

Lesson 3/8Chapter 2: Functions

Core Function Concepts

Essential concepts every JavaScript developer should understand

Function Declaration (Khai báo hàm)

Hàm được khai báo với từ khóa function và có thể được gọi trước khi định nghĩa do hoisting.

function chaoHoi(ten) { return `Xin chào, ${ten}!`; }

Function Expression (Biểu thức hàm)

Hàm được gán cho một biến và không có hoisting.

const chaoHoi = function(ten) { return `Xin chào, ${ten}!`; };

Arrow Function (Hàm mũi tên)

Cú pháp ngắn gọn cho hàm, không có this riêng và không có hoisting.

const chaoHoi = (ten) => `Xin chào, ${ten}!`;

Closure (Bao đóng)

Hàm có thể truy cập biến từ phạm vi bên ngoài ngay cả sau khi phạm vi đó đã kết thúc.

function ngoai(x) { return function(y) { return x + y; }; }

Higher-Order Function (Hàm bậc cao)

Hàm nhận hàm khác làm tham số hoặc trả về một hàm.

function map(mang, hamXuLy) { return mang.map(hamXuLy); }

IIFE (Immediately Invoked Function Expression)

Hàm được thực thi ngay lập tức sau khi được định nghĩa.

(function() { console.log('IIFE đã thực thi!'); })();

Function Types Comparison

Key differences between function declarations, expressions, and arrow functions

AspectFunction DeclarationFunction ExpressionArrow Function
HoistingCó hoisting đầy đủKhông có hoistingKhông có hoisting
this bindingDynamic thisDynamic thisLexical this
arguments objectCó sẵnCó sẵnKhông có
ConstructorCó thể dùng newCó thể dùng newKhông thể dùng new
Cú phápfunction name() {}const name = function() {}const name = () => {}

Best Practices

Follow these guidelines for clean, maintainable function code

Đặt tên hàm có ý nghĩa

Sử dụng tên động từ mô tả chức năng của hàm

Good Practice Example

javascript
// Tốt
function calculateTotalPrice(items) { ... }
function validateEmail(email) { ... }
// Không tốt
function calc(items) { ... }
function check(email) { ... }

Hàm chỉ nên làm một việc

Mỗi hàm chỉ nên có một trách nhiệm duy nhất (Single Responsibility)

Good Practice Example

javascript
// Tốt
function calculateTax(price) { ... }
function formatCurrency(amount) { ... }
// Không tốt
function calculateAndFormatPrice(price) {
// Làm nhiều việc cùng lúc
}

Sử dụng const cho function expressions

Tránh reassignment không mong muốn

Good Practice Example

javascript
// Tốt
const calculateTotal = (items) => { ... };
// Không tốt
let calculateTotal = (items) => { ... };

Trả về sớm để tránh nesting

Sử dụng early return để code dễ đọc hơn

Good Practice Example

javascript
// Tốt
function processUser(user) {
if (!user) return null;
if (!user.isActive) return null;
return processActiveUser(user);
}
// Không tốt
function processUser(user) {
if (user) {
if (user.isActive) {
return processActiveUser(user);
}
}
return null;
}

Common Mistakes

Avoid these frequent pitfalls when working with functions

Gọi function expression trước khi khai báo

⚠️ Problem

javascript
// Lỗi
sayHello(); // ReferenceError
const sayHello = () => console.log("Hello");
// Đúng
const sayHello = () => console.log("Hello");
sayHello(); // "Hello"

✅ Solution

javascript
Khai báo function expression trước khi sử dụng

Sử dụng arrow function cho methods cần this

⚠️ Problem

javascript
// Lỗi
const obj = {
name: "Test",
greet: () => console.log(this.name) // undefined
};
// Đúng
const obj = {
name: "Test",
greet() { console.log(this.name) } // "Test"
};

✅ Solution

javascript
Sử dụng regular function cho object methods

Quên return trong arrow function nhiều dòng

⚠️ Problem

javascript
// Lỗi
const calculate = (x, y) => {
const result = x * y;
// Quên return
};
// Đúng
const calculate = (x, y) => {
const result = x * y;
return result;
};

✅ Solution

javascript
Luôn có return statement khi cần giá trị trả về

Mục lục

Không có mục lục