Home >Web Front-end >JS Tutorial >Why is JavaScript not a mess?
The common complaint that frontend development, particularly JavaScript, is a chaotic mess often stems from its flexibility. The ability to achieve the same outcome through multiple approaches, while powerful, can lead to inconsistent code quality.
This isn't entirely inaccurate. Unlike backend development, which often benefits from established frameworks and conventions, frontend best practices are more diffuse. Resources on optimal patterns are scattered, fostering diverse coding styles and making it challenging for newcomers to grasp optimal approaches.
The lack of readily apparent structure doesn't imply an absence of best practices. Effective JavaScript development hinges on leveraging established patterns and efficient methods. Abundant resources, such as the Mozilla Developer Network (MDN) JavaScript documentation, provide guidance on optimal implementations. The key is dedicated learning and applying this knowledge.
Consider this real-world production code snippet (simplified for clarity): It functions correctly, but its structure could be significantly improved for readability and performance. The example focuses on basic array and object manipulation.
Initial Code (Less Ideal):
<code class="language-javascript">const storesList = [{ activeStories: [ { name: 'Starbucks', code: 1 }, { name: 'Duck Duck Coffe', code: 2 } ], inactiveStories: [ { name: 'Mac Coffe', code: 3 } ] }] storesList.reduce((previous, current) => { current.activeStories.forEach(store => { previous.push({ ...store, label: `Opened ${store.name}` }) }) return previous }, []) // result: // [ // { // "name": "Starbucks", // "code": 1, // "label": "Opened Starbucks" // }, // { // "name": "Duck Duck Coffe", // "code": 2, // "label": "Opened Duck Duck Coffe" // } // ]</code>
This approach, using .reduce
and .forEach
, is unnecessarily verbose. JavaScript offers more efficient tools.
Improved Code:
<code class="language-javascript">storesList.flatMap((item) => { return item.activeStories }).map((item) => { return { ...item, label: `Opened ${item.name}` } })</code>
This revised version utilizes .flatMap
to flatten the array and .map
to add the "label" property, resulting in cleaner, more concise code.
JavaScript offers a rich set of tools for crafting high-quality code. The key is dedicated learning and the application of appropriate techniques, rather than simply writing code for the sake of functionality.
The above is the detailed content of Why is JavaScript not a mess?. For more information, please follow other related articles on the PHP Chinese website!