Top ten Javascript tricks part 5

“for in” vs “for of”

for(a in 'ab'){
console.log(a)
}
//0
//1

for(a of 'ab'){
console.log(a)
}
//a
//b

Record Timing

console.log('timer')
setTimeout(() => console.log, 1000)
console.timeEnd('timer')
// result: timer: 0.056884765625ms

Fibonacci sequence algorithm in Javascript

//while loop
function fibonacci(num){
let a = 1, b = 0 , temp;
while(num >= 0){
temp = a;
a = a + b;
b = temp;
num--;
}
return b;
}

//Recursive solution
function fibonacci(num){
if(num <= 1) return 1;
return fibonacci(num - 1) + fibonacci(num - 2);
}

//Memization
function fibonacci(num, memo){
memo = memo || {};
if(memo[num]) return memo[num];
if(num <= 1) return 1;
return memo[num] = fibonacci(num - 1, memo) + fibonacci(num - 2, memo)
}

One time event listeners in Javascript

const button = document.getElementById('button');

button.addEventListener("click", () => {
console.log('I will fire only once');
}, {once: true})

Private field declaration in es6 class

In Es6, private class fields are defined using a hash # prefix.
You can start using them today with babel7 and stage 3 preset

class Something{
#property;

constructor() {
this.#property = "Test property";
}
}

const instance =  new Something();
console.log(instance.property);
//Result: undefined

Code validator in new Es2020 features are now finalized

//old way
user && user.address && user.address.house &&
console.log(user.address.house.number)

// do this Es2020 beatury
console.log(user?.address?.house?.number)

Pipeline Operator

The experimental pipeline operator |> (current stage at 1) pipes the value of an expression into a function.
This allows the creation of chained function calls in a readable manner.
The result is syntactic sugar in which a function call with a single argument.
As of now, there is no Browser compatibility.

function doubleSay(str){
return str +", "+ str
}

function capitalize(str){
return str[0].toUpperCase() + str.substring(1)
}

function exclaim(str){
return str + '!'
}

let result = exclaim(capitalize(doubleSay("helperscript")))
console.log(result) // "Helperscript helperscript!"

result = "helperscript" |> doubleSay |> capitalize |> exclaim
console.log(result) // "Helperscript, helperscript!"

Static Vs Dynamic Import

import React from 'react';
// module exported with default keyword

import { FC } from 'react';
// module exported without default keyword

// Dynamic import
import('path/to/module.js').then((module) =>{
...
})

//or inside an async function
const module = await import('path/to/module.js');

Javascript padStart() and padEnd()

padStart() – The padding applied from start of string
padEnd() – Then padding applied from end of string

'helperscript'.padStart(14); // "  helperscript"
// if padString given
'helperscript'.padStart(14, '#') // "##helperscript"

//if padString not given
'helperscript'.padEnd(14) // "helperscript  "

// if padString given
'helperscript'.padEnd(14, '#') // "helperscript##"

String() Vs .toString() in javascript

The String () method converts anything into a string.
The toString() method converts numbers and booleans to a string.

String(68) // "68"
String(null) // "null"
String(undefined) //  "undefined"
String(true) // "true"


// toString()
(68).toString(); //"68"
(true).toString(); // "true"
(null).toString(); // TypeError
(undefined).toString(); // TypeError

But Unlike the String() method, the .toString() method will throw a TypeError, when used with null or undefined

Have a great day! Comment if any queries.

< Javascript tricks part 4

2 thoughts on “Top ten Javascript tricks part 5”

  1. Everything is very open with a really clear explanation of the issues. It was truly informative. Your site is very helpful. Many thanks for sharing. Tamiko Cullen Loutitia

Leave a Reply

Your email address will not be published. Required fields are marked *