// Good const userAge = 25; function calculateTotalPrice(items) { ... } // Bad const a = 25; function calc(items) { ... }
const userAge = 25; function calculateTotalPrice(items) { ... } class UserProfile { ... }
// Good function calculateDiscount(price, discount) { ... } const price1 = calculateDiscount(100, 10); const price2 = calculateDiscount(200, 20); // Bad const price1 = 100 - 10; const price2 = 200 - 20;
async function fetchData() { try { const response = await fetch('api/url'); const data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); } }
function getUserAge(user) { if (!user || !user.age) { return 'Age not available'; } return user.age; }
if (condition) { doSomething(); } else { doSomethingElse(); }
// utils.js export function calculateDiscount(price, discount) { ... } // main.js import { calculateDiscount } from './utils.js';
// ui.js function updateUI(data) { ... } // data.js async function fetchData() { ... } // main.js import { updateUI } from './ui.js'; import { fetchData } from './data.js';
'use strict';
const MAX_USERS = 100;
// Good (function() { const localVariable = 'This is local'; })(); // Bad var globalVariable = 'This is global';
/** * Calculates the total price after applying a discount. * @param {number} price - The original price. * @param {number} discount - The discount to apply. * @returns {number} - The total price after discount. */ function calculateTotalPrice(price, discount) { ... }
// Good async function fetchData() { try { const response = await fetch('api/url'); const data = await response.json(); return data; } catch (error) { console.error('Error fetching data:', error); } } // Bad function fetchData(callback) { fetch('api/url') .then(response => response.json()) .then(data => callback(data)) .catch(error => console.error('Error fetching data:', error)); }
// Good const vehicle = { make: 'Toyota', model: 'Camry' }; const { make, model } = vehicle; // Bad const vehicleMake = vehicle.make; const vehicleModel = vehicle.model;
透過遵循這些標準,您可以確保您的 JavaScript 程式碼乾淨、可維護且有效率。
以上是通用編碼標準 JavaScript。的詳細內容。更多資訊請關注PHP中文網其他相關文章!