Skip to content

Instantly share code, notes, and snippets.

@johnborges
Last active December 24, 2020 00:07
Show Gist options
  • Save johnborges/e13db05ced9b4b2dca882391a7e9ee9e to your computer and use it in GitHub Desktop.
Save johnborges/e13db05ced9b4b2dca882391a7e9ee9e to your computer and use it in GitHub Desktop.

String to Number

my_string = "123";
console.log(+my_string);
// 123

my_string = "amazing";
console.log(+my_string);
// NaN

Get Unique Values

let array_values = [1, 3, 3, 4, 5, 6, 6, 6,8, 4, 1]
let unique_values = [...new Set(array_values )];
console.log(unique_values );
// [1,3, 4, 5, 6, 8]

Nullish coalescing operator

// here's what we often did for this:
x = x || 'some default'
// but this was problematic for numbers or booleans where "0" or "false" are valid values
// So, if we wanted to support this:
add(null, 3)
// here's what we had to do before:
function add(a, b) {
  a = a == null ? 0 : a
  b = b == null ? 0 : b
  return a + b
}
// here's what we can do now
function add(a, b) {
  a = a ?? 0
  b = b ?? 0
  return a + b
}

Optional Chaining

The optional chaining operator (?.) permits reading the value of a property located deep within a chain of connected objects without having to expressly validate that each reference in the chain is valid.

Let's consider the expression a?.b.

This expression evaluates to a.b if a is not null and not undefined, otherwise, it evaluates to undefined.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment