Nice Javascript

Nice Javascript

🎯 Min-Max shorthand

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
// If argument is less than min value, set min value.
// If argument is greater than max value, set max value.
// Otherwise set the argument value.

const max = 100;
const min = 0;

const validate1 = (num) => {
let result = num;
if (num < min) {
result = min;
}

if (num > max) {
result = max;
}

console.log('validate1:', result);
};
validate1(50);

// This way is way cleaner :D
const validate2 = (num) => {
const result = Math.min(Math.max(num, min), max);
console.log('validate2:', result);
};

validate2(50);

🎯 Curly brackets in console.log

1
2
3
4
5
6
7
8
9
10
// Curly brackets in console.log turns the value into object with key
const hoe = 'HOE';

console.log(hoe);
HOE;

console.log({ hoe });
{
hoe: 'HOE';
}

Curly brackets in console.log


🎯 Bang Bang

1
!!0; // this returns false 😵

!!0


🎯 Typescript - Type

Typescript_Type


🎯 Immediately Invoked Function Expression(IIFE)

1
2
3
4
5
6
7
8
9
10
// ver1: Ah I can find it everywhere :D
;(function(){
console.log('Hello, World!');
})();


// Ver2: Oh! Shorter... (-_-)
~(_=>
console.log('Hello, World!')
)``;

🎯 Simple Heavy work and Sleep method

1
2
// Promise method
const sleep = (delay) => new Promise((resolve) => setTimeout(resolve, delay));
1
2
3
4
5
// heavy task method
const heavyTask = () => {
let i = 0;
while (i < 2000000000) i++;
};
1
2
3
4
5
// sleep method
const sleep = (delay) => {
const start = new Date().getTime();
while (new Date().getTime() < start + delay);
};

🎯 Display JSON data

1
<pre>{JSON.stringify(data, null, 2)}</pre>

🎯 Add to array with if condition

1
2
3
4
5
6
7
8
9
const flag = false;

const arr = [
1,
...(flag ? [2] : []),
3
]

console.log(arr) // [1, 3]

🎯 Short hand of switch

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
const one = () => console.log('ONE');
const two = () => console.log('TWO');
const three = () => console.log('THREE');

const flag = 'foo';

// short hand
const data = {
foo: one,
bar: two,
baz: three
};

data[flag] && data[flag](); // ONE

// long hand
switch (flag) {
case 'foo':
one();
break;
case 'bar':
two();
break;
case 'baz':
three();
break;
default:
console.log('hmmm...')
}; // ONE

🎯 Build full name from data object

1
2
3
4
5
6
7
8
9
const data = {
firstName: 'First',
middleName: '',
lastName: 'Last',
};

const fullName = Object.values(data).filter(val => val).join(' ');

console.log(fullName); // First Last

🎯 ?? vs ||

?? checks only null or undefined.
|| checks false(boolean), ''(empty string), 0(number), null and undefined.


Demo on Typescript Playground