DEV Community

Cover image for Mastering JavaScript Shorthands
Leandro Nuñez for Digital Pollution

Posted on Edited on

Mastering JavaScript Shorthands

Hey there, fellow JavaScript enthusiasts!

Leandro Nuñez, your trusty software engineer, is back with some JavaScript magic.

Today, we'll explore the art of JavaScript shorthands - nifty techniques that make your code more concise and elegant.
We'll dive into real use case examples in both vanilla JavaScript and the shorthand form.

So buckle up, and let's elevate your JavaScript skills to new heights!

1. The Ternary Operator:

Use Case: Conditional Assignment

Normal JavaScript:

let isAdmin;
if (user.role === 'admin') {
  isAdmin = true;
} else {
  isAdmin = false;
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const isAdmin = user.role === 'admin' ? true : false;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorterhand thanks @jonrandy

const isAdmin = user.role === 'admin';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

2. Object Property Shorthand:

Use Case: Creating Objects with Variables

Normal JavaScript:

const name = 'Leandro';
const age = 30;

const person = {
  name: name,
  age: age
};
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const name = 'Leandro';
const age = 30;

const person = {
  name,
  age
};
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

3. Default Parameter Values:

Use Case: Providing Default Values to Function Parameters

Normal JavaScript:

function greet(name) {
  name = name || 'Guest';
  return `Hello, ${name}!`;
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

function greet(name = 'Guest') {
  return `Hello, ${name}!`;
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Caution: be careful with this one. Check out this comment by @efpage here

4. Short-Circuit Evaluation:

Use Case: Fallback for Undefined or Null Values

Normal JavaScript:

const username = getUsernameFromAPI();
const displayName = username ? username : 'Anonymous';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const username = getUsernameFromAPI();
const displayName = username || 'Anonymous';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

5. Array Destructuring:

Use Case: Swapping Variables

Normal JavaScript:

let a = 5;
let b = 10;

const temp = a;
a = b;
b = temp;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

let a = 5;
let b = 10;

[a, b] = [b, a];
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

6. Template Literals:

Use Case: Dynamic String Concatenation

Normal JavaScript:

const name = 'Leandro';
const greeting = 'Hello, ' + name + '!';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const name = 'Leandro';
const greeting = `Hello, ${name}!`;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

7. Arrow Functions:

Use Case: Concise Function Definitions

Normal JavaScript:

function add(a, b) {
  return a + b;
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const add = (a, b) => a + b;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

8. Nullish Coalescing Operator:

Use Case: Providing Default Values for Null or Undefined Variables

Normal JavaScript:

const data = fetchUserData();
const username = data !== null && data !== undefined ? data.username : 'Guest';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const data = fetchUserData();
const username = data ?? 'Guest';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

9. Object Destructuring:

Use Case: Extracting Object Properties into Variables

Normal JavaScript:

const user = {
  name: 'Leandro',
  age: 30,
  country: 'USA'
};

const name = user.name;
const age = user.age;
const country = user.country;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const user = {
  name: 'Leandro',
  age: 30,
  country: 'USA'
};

const { name, age, country } = user;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

10. Spread Operator:

Use Case: Merging Arrays or Objects

Normal JavaScript:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = arr1.concat(arr2);
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

const arr1 = [1, 2, 3];
const arr2 = [4, 5, 6];
const mergedArray = [...arr1, ...arr2];
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

11. Logical OR Assignment:

Use Case: Assigning a Default Value to a Variable

Normal JavaScript:

let count;
if (!count) {
  count = 0;
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

let count;
count ||= 0;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

12. Short-Circuit Evaluation for Function Call:

Use Case: Avoiding Unnecessary Function Execution

Normal JavaScript:

function fetchData() {
  if (shouldFetchData) {
    return fetchDataFromAPI();
  } else {
    return null;
  }
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorthand:

function fetchData() {
  return shouldFetchData && fetchDataFromAPI();
}
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

There you have it!

JavaScript shorthands continue to impress with their elegance and efficiency.
Incorporate these concise examples into your codebase, and watch your JavaScript skills soar to new heights.

Happy coding and enjoy unleashing the power of JavaScript shorthands in your projects! 🚀

Top comments (8)

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
efpage profile image
Eckehard •

Version 3 may cause trouble, as shorthand behaves differently:

function test(name1, name2 = 'Guest') {
   name1 = name1 || 'Guest';
   console.log(name1, name2)
}
    test("test", "test") // -> test test
    test() // -> Guest Guest
    test(false, false) // -> Guest false
    test(null, null) // -> Guest null
    test(0, 0) // -> Guest 0
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Default function parameters are used, if the argument is undefined, while the || checks for false. In Javascript, any nullish value is treated as false.

It work better, if you use nullish coalescing operator (??), but even that fails if you provide null as an argument (which usually does not happen accidentially):

    function test(name1, name2 = 'Guest') {
      name1 = name1 ?? 'Guest';
      console.log(name1, name2)
    }
    test(null, null) // -> Guest null
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

In most cases the default parameters are the better solution, but there are situations where you need to set defaults in your code. It seems, there is no shorthand for all cases:

   name1 = typeof(name1) !==='undefined' ?  name1 : 'Guest';
   if (typeof(name1) !==='undefined' ) name1  =  'Guest'
  // ----- use a default() function --------
   const default = (val, def) => 
        (typeof(val) === 'undefined') ? def : val

   val = default(val, "Guest") // 
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
leandro_nnz profile image
Leandro Nuñez Digital Pollution •

Thanks! I linked a caution to this excellent explained comment.

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
jonrandy profile image
Jon Randy 🎖️ •

Shorthand:

const isAdmin = user.role === 'admin' ? true : false;
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini

Shorterhand:

const isAdmin = user.role === 'admin';
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini ⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
leandro_nnz profile image
Leandro Nuñez Digital Pollution •

I added this to the post. Thank you so much!

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
fruntend profile image
fruntend •

Сongratulations 🥳! Your article hit the top posts for the week - dev.to/fruntend/top-10-posts-for-f...
Keep it up 👍

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
onlinemsr profile image
Raja MSR • • Edited

Thanks for sharing!

Ternary operator is best choice for simple statements. If we go for nested ternary, it leads to confusion.

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
leandro_nnz profile image
Leandro Nuñez Digital Pollution •

IME, anything can lead to confusion 😂😂😂. One should never stop learning.
Thanks for your comment!

⚡ Match Highlights: digitalpollution/mastering javascript shorthands mg - Pertandingan Hari Ini
 
jonrandy profile image
Jon Randy 🎖️ •

The examples in 12 are not equivalent