// 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中文网其他相关文章!