Show‑off JavaScript Techniques to Impress Others
The article showcases a suite of flashy JavaScript tricks—alternative anonymous‑function syntaxes, the void operator for undefined, logical‑operator conditionals, optional semicolons, early ES6 features, AMD wrapping, the Function constructor, and native DOM selectors—while warning that some shortcuts hurt readability and should be used sparingly.
This article presents a collection of JavaScript tricks aimed at making code look more sophisticated and impressive to readers.
1. Various anonymous function syntaxes – Besides the usual way of writing an anonymous function, the article shows alternative forms that rely on high‑precedence operators such as +, -, !, ~ to invoke the function immediately, purely for stylistic effect.
2. An alternative way to produce undefined – It explains that JavaScript automatically assigns undefined to uninitialized variables, and demonstrates the use of the void operator (e.g., void(0) ) to explicitly yield undefined , noting that this pattern is often seen in javascript:void(0) links.
3. Replacing if / else with logical operators – The article shows how logical OR ( || ) and AND ( && ) can be used to simplify conditional logic, and how double‑negation ( !! ) can be employed to coerce truthy/falsy values.
4. Omitting semicolons – It discusses the long‑standing debate about automatic semicolon insertion, stating that omitting semicolons can be seen as a “high‑class” style if the code is written safely.
5. Jumping on the ES6 early‑train – The article encourages using ES6 features such as module , class , and Map , and at minimum adding "use strict" for ES5 code.
6. Adding AMD module support – It suggests wrapping code in an AMD definition so that other projects can load it via the AMD loader, providing a fallback to a global object when AMD is unavailable.
7. Using the Function constructor – The piece explains that the capital‑F Function constructor can create functions from strings, which can be useful when eval is prohibited, such as in template engines or JSON‑to‑function conversions.
8. Using native DOM APIs instead of jQuery – It argues that modern browsers’ querySelector and querySelectorAll can replace most jQuery functionality, allowing a “jQuery‑free” approach.
Conclusion – Some of the showcased tricks improve readability or performance (e.g., logical‑operator shortcuts), while others (e.g., void 0 ) make code obscure and are discouraged. The key is to use such techniques judiciously so that the code remains maintainable and impressive.
Baidu Tech Salon
Baidu Tech Salon, organized by Baidu's Technology Management Department, is a monthly offline event that shares cutting‑edge tech trends from Baidu and the industry, providing a free platform for mid‑to‑senior engineers to exchange ideas.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.