ES6+ Modern JavaScript, Node.js Backend, React/Vue Frontend
// Arrow functions
const greet = (name) => `Xin chào, ${name}!`;
const add = (a, b) => a + b;
// Destructuring - Objects
const user = { name: 'An', age: 25, city: 'HCM' };
const { name, age } = user;
// Destructuring - Arrays
const colors = ['red', 'green', 'blue'];
const [first, second, ...rest] = colors;
// Destructuring in function params
const displayUser = ({ name, age }) => {
console.log(`${name} - ${age} tuổi`);
};
displayUser(user);
// Default parameters
const createUser = (name, role = 'user') => ({
name,
role,
createdAt: new Date()
});
// Fetch API với async/await
const fetchUsers = async () => {
try {
const response = await fetch('https://api.example.com/users');
if (!response.ok) {
throw new Error(`HTTP error! status: ${response.status}`);
}
const users = await response.json();
return users;
} catch (error) {
console.error('Lỗi:', error.message);
throw error;
}
};
// Parallel requests
const fetchAllData = async () => {
const [users, posts, comments] = await Promise.all([
fetch('/api/users').then(r => r.json()),
fetch('/api/posts').then(r => r.json()),
fetch('/api/comments').then(r => r.json())
]);
return { users, posts, comments };
};
const user = {
name: 'An',
address: {
city: 'HCM'
}
};
// Optional chaining (?.)
const country = user?.address?.country; // undefined (không lỗi)
const street = user?.address?.street?.name;
// Nullish coalescing (??)
const defaultCity = user?.address?.city ?? 'Chưa có'; // 'HCM'
const defaultCountry = country ?? 'Vietnam'; // 'Vietnam'
// Kết hợp với function calls
const getConfig = (options) => {
return {
timeout: options?.timeout ?? 5000,
retries: options?.retries ?? 3
};
};
import express from 'express';
import cors from 'cors';
const app = express();
const PORT = process.env.PORT || 3000;
// Middleware
app.use(cors());
app.use(express.json());
// In-memory data
const users = [
{ id: 1, name: 'An', email: 'an@example.com' },
{ id: 2, name: 'Bình', email: 'binh@example.com' }
];
// Routes
app.get('/api/users', (req, res) => {
res.json({ success: true, data: users });
});
app.get('/api/users/:id', (req, res) => {
const user = users.find(u => u.id === parseInt(req.params.id));
if (!user) {
return res.status(404).json({
success: false,
message: 'User not found'
});
}
res.json({ success: true, data: user });
});
app.post('/api/users', (req, res) => {
const { name, email } = req.body;
const newUser = {
id: users.length + 1,
name,
email
};
users.push(newUser);
res.status(201).json({ success: true, data: newUser });
});
app.listen(PORT, () => {
console.log(`Server running on port ${PORT}`);
});
import { useState, useEffect, useCallback } from 'react';
// Custom hook cho fetch data
const useFetch = (url) => {
const [data, setData] = useState(null);
const [loading, setLoading] = useState(true);
const [error, setError] = useState(null);
useEffect(() => {
const fetchData = async () => {
try {
const response = await fetch(url);
const json = await response.json();
setData(json);
} catch (err) {
setError(err.message);
} finally {
setLoading(false);
}
};
fetchData();
}, [url]);
return { data, loading, error };
};
// Component sử dụng hook
const UserList = () => {
const { data: users, loading, error } = useFetch('/api/users');
if (loading) return <div>Đang tải...</div>;
if (error) return <div>Lỗi: {error}</div>;
return (
<ul>
{users.map(user => (
<li key={user.id}>{user.name}</li>
))}
</ul>
);
};
// Interfaces
interface User {
id: number;
name: string;
email: string;
role: 'admin' | 'user' | 'guest';
createdAt?: Date;
}
// Generic function
async function fetchData<T>(url: string): Promise<T> {
const response = await fetch(url);
return response.json();
}
// Usage
const users = await fetchData<User[]>('/api/users');
// Type guards
function isAdmin(user: User): boolean {
return user.role === 'admin';
}
// Utility types
type CreateUserInput = Omit<User, 'id' | 'createdAt'>;
type UserSummary = Pick<User, 'id' | 'name'>;
type PartialUser = Partial<User>;
• MDN JavaScript
• React
Documentation
• Dịch vụ lập trình ứng dụng - Không Gian AI