12 Little‑Known JavaScript Tricks Every Developer Should Know

This article reveals twelve obscure JavaScript features—from the function length property and the versatile void operator to advanced uses of optional chaining, Symbol.asyncIterator, and the Intl API—providing practical code examples and visual illustrations for modern web developers.

JavaScript
JavaScript
JavaScript
12 Little‑Known JavaScript Tricks Every Developer Should Know

Although we are quite familiar with JavaScript, the language still contains many interesting features and behaviors. Today we share twelve little‑known JavaScript facts.

1. Function length property

Just as arrays have a length property, functions do too. The length property returns the number of parameters the function expects (excluding those with default values).

function foo(a, b, c = 3) { return a + b + c; }
console.log(foo.length); // 2, default parameters not counted

function bar(a, b = 2, c) { return a + b + c; }
console.log(bar.length); // 1, parameters after first default are ignored

(() => {}).length; // 0
((...args) => {}).length; // 0

This is especially useful when writing higher‑order functions or doing functional‑style parameter matching.

2. The void operator does more than return undefined

The void operator can be used to suppress a return value and solve several special problems.

// 1. Prevent arrow function from returning a value
const onClick = () => void doSomething();

// 2. Create a pure undefined
let undefined = 'hello';
console.log(void 0); // undefined

// 3. Immediately execute a Promise
void Promise.resolve().then(() => {
  console.log('异步执行');
});

// 4. Prevent default href navigation
<a href="javascript:void(0)">点击</a>

3. Changes to Function.prototype.toString()

Since ES2019, Function.prototype.toString() preserves the original source code, including comments and whitespace.

function /* 这是注释 */ foo() {
  console.log("Hello"); // 这也是注释
}
console.log(foo.toString());
// function /* 这是注释 */ foo() {
//   console.log("Hello"); // 这也是注释
// }

// Even works for built‑in functions
console.log(Array.prototype.push.toString());
// "function push() { [native code] }"

4. Hidden uses of the comma operator

The comma operator can be employed in unexpected places such as arrow functions or ternary expressions.

// In arrow function execute multiple statements
const increment = x => (console.log(x), x + 1);

// In ternary operator execute several actions
const result = condition
  ? (func1(), func2(), value1)
  : (func3(), func4(), value2);

// In array method cleverly use
const arr = [1, 2, 3];
arr.map(x => (x *= 2, x -= 1)); // [1, 3, 5]

5. Optional chaining tricks

The optional‑chaining operator can be used not only for property access but also for function calls and array indexing.

// Function call
const result = someFunction?.();

// Array access
const arr = null;
console.log(arr?.[0]); // undefined

// Dynamic property name
const propName = null;
console.log(obj?.[propName?.toString()]); // undefined

// Combine with nullish coalescing
const value = obj?.prop ?? 'default';

6. Creative use of Symbol.asyncIterator

You can create custom asynchronous iterators using Symbol.asyncIterator.

7. Defining truly constant objects with Object.defineProperty

By using Object.defineProperty, you can create objects whose properties are completely immutable.

8. Clever uses of the label statement

Although rarely seen, label statements are handy in certain scenarios, especially for breaking out of nested loops.

9. Simulating private properties with Proxy

Before class private fields became widely supported, Proxy could be used to emulate private properties.

10. Implementing range types with Generators

JavaScript lacks a native range type, but a generator can provide similar functionality.

11. Unexpected behavior of BigInt

BigInt exhibits some surprising characteristics.

12. Powerful features of the Intl API

The Intl API goes beyond date and number formatting, offering many advanced capabilities.

// Relative time formatting
const rtf = new Intl.RelativeTimeFormat('zh', { numeric: 'auto' });
console.log(rtf.format(-1, 'day')); // "昨天"
console.log(rtf.format(7, 'day')); // "7天后"

// Plural rules
const pr = new Intl.PluralRules('en-US');
console.log(pr.select(0)); // "other"
console.log(pr.select(1)); // "one"
console.log(pr.select(2)); // "other"

// Segmenter
const segmenter = new Intl.Segmenter('zh', { granularity: 'word' });
const segments = segmenter.segment('你好,世界!');
console.log([...segments].map(s => s.segment)); // ["你好", ",", "世界", "!"]

Feel free to add more examples.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

JavaScriptWeb Developmentprogramming tipsES2020Advanced JavaScript
JavaScript
Written by

JavaScript

Provides JavaScript enthusiasts with tutorials and experience sharing on web front‑end technologies, including JavaScript, Node.js, Deno, Vue.js, React, Angular, HTML5, CSS3, and more.

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.