DEV Community

Helder Burato Berto
Helder Burato Berto

Posted on

3 2

🔥 Quick Tip: What's the benefit of using - Nullish Coalescing operator

On this simple trick, I'll show you the benefit of using Nullish Coalescing - ?? instead of OR - ||.

const user = {
  name: '',
  isDev: undefined,
  isHuman: false,
  age: 0,
};

// Using ?? operator
console.log(user.name ?? 'John Doe'); // => ''
console.log(user.isDev ?? false); // => false
console.log(user.isHuman ?? true); // => false
console.log(user.age ?? 20); // => 0

// ----

// Using || operator
console.log(user.name || 'John Doe'); // => 'John Doe'
console.log(user.isDev || false); // => false
console.log(user.isHuman || true); // => true
console.log(user.age || 20); // => 20
Enter fullscreen mode Exit fullscreen mode

Notice in some cases with different values from null or undefined the operator || isn't get a wanted value.

Note: You can use this feature with babel or another compiler enabling the ES2020 features.

Reference


Did you like it? Comment, share! ✨

SurveyJS custom survey software

Build Your Own Forms without Manual Coding

SurveyJS UI libraries let you build a JSON-based form management system that integrates with any backend, giving you full control over your data with no user limits. Includes support for custom question types, skip logic, an integrated CSS editor, PDF export, real-time analytics, and more.

Learn more

Top comments (0)

Postmark Image

Speedy emails, satisfied customers

Are delayed transactional emails costing you user satisfaction? Postmark delivers your emails almost instantly, keeping your customers happy and connected.

Sign up