Hidden Javascript features

Here are some uncommon or little known used javascript features const b = template` wait what? `

Hidden Javascript features

Here are some uncommon or little known used javascript features

updated 20211220
updated 20211225 svelte addition
updated 20220125 for spead string tirck

Tagged Template Literals (es6 only)

from mdn

Tags allow you to parse template literals with a function. The first argument of a tag function contains an array of string values. The remaining arguments are related to the expressions.

source developer.mozilla.org

If you’ve never seen styled-components before, this weird "button ``" syntax looks

const Button = styled.button`
  background-color: papayawhip;
  border-radius: 3px;
  color: palevioletred;
`

great rightup for how it works

const favoriteFood = 'pizza'
const favoriteDrink = 'obi'

logArgs`I like ${favoriteFood} and ${favoriteDrink}.`
// -> ["I like ", " and ", "."] "pizza" "obi"
from the bellow article
The magic behind 💅 styled-components
Never seen that magic backtick styled.div`` notation? It’s actually just JavaScript, no fancy transpiler needed! What that is, how it works and what it does? Let’s find out!

?.Optional chaining

object.with.lots.of.nested.stuff
const adventurer = {
  name: 'Alice',
  cat: {
    name: 'Dinah'
  }
};

const dogName = adventurer.dog?.name;
console.log(dogName);
// expected output: undefined

console.log(adventurer.someNonExistentMethod?.());
// expected output: undefined

this will return undefined instead of error out useful when using network javascript objects that may not exist

Array item access with optional chaining

let arrayItem = arr?.[42];
Optional chaining (?.) - JavaScript | MDN
The optional chaining operator (?.) enables you to read the value of a property located deep within a chain of connected objects without having to check that each reference in the chain is valid.

Nullish coalescing operator (??)

a safer replacement for || when using default values

const foo = null ?? 'default string';
console.log(foo);
// expected output: "default string"

const baz = 0 ?? 42;
console.log(baz);
// expected output: 0

Mdn saids it best

""""

Earlier, when one wanted to assign a default value to a variable, a common pattern was to use the logical OR operator (||):

let foo;

//  foo is never assigned any value so it is still undefined
let someDummyText = foo || 'Hello!';

However, due to || being a boolean logical operator, the left hand-side operand was coerced to a boolean for the evaluation and any falsy value (0, '', NaN, null, undefined) was not returned. This behavior may cause unexpected consequences if you consider 0, '', or NaN as valid values.

"""" - source

What about `labels`?

label - JavaScript | MDN

foo: {
  console.log('face');
  break foo;
  console.log('this will not be executed');
}
console.log('swap');

// this will log:

// "face"
// "swap" 

Update!

turns out svelte the react replacement UI framework uses templates heavly!

Source Docs • Svelte


For of loops with async functions!

for await...of - JavaScript | MDN

const asyncIterable = {
  [Symbol.asyncIterator]() {
    return {
      i: 0,
      next() {
        if (this.i < 3) {
          return Promise.resolve({ value: this.i++, done: false });
        }

        return Promise.resolve({ done: true });
      }
    };
  }
};

(async function() {
   for await (let num of asyncIterable) {
     console.log(num);
   }
})();

// 0
// 1
// 2

Raw template Literals aka `words`

this allows you to have non escaped control characters! nice!

(text version of images above)

String.raw`works with newlines\n`
'works with newlines\\n'
sssString.raw`also tabs \t?`
'also tabs \\t?'

Cool trick: String to Character Array

ever wanted to convert an string into array of characters?
usefull when you want to do a array operation that is not availbe on strings

Code

alphabet = [..."ABCDEFGHIJKLMNOPQRSTUVWXYZ"]
> ["A", "B", "C", "D", "E", "F", "G", "H", "I", …]

Take Note of the ..."abce"

Other usefull exampling using this trick

code bellow gets all the unique characters within a string

duplicates = new Set( [..."AAABBBCC"])
> Array(duplicates) //convert back to array of unque values
  ["A", "B", "C"]
or back to string
 Array(duplicates).join("") 
> "ABC"

Source: i found this cool hacker while looking at d3.js's tutorial

Learn D3: Joins / D3 / Observable

Author

by oran collins
github.com/wisehackermonkey
oranbusiness ╚(•⌂•)╝ gmail (●'◡'●) com
20211220
I use a tracker that is pravicy focused so if you block its cool, im big on blocking stuff on my own machine. im doing it to see if anyone is actualy reading my blog posts...:)