Hidden Javascript features
Here are some uncommon or little known used javascript features const b = template` wait what? `
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
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"
?.
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];
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`?
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