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

Top ten Javascript tricks part 4

Throw an error when parameters required for function

const requireParam = () => {
thorw new Error('This parameter is required')
}

const sumNumbers = (val1 = requiredParam(), val2 = requiredParam()) => {
return val1 + val2
}

sumNumbers(4, 5)
//Result: 9

sumNumbers(4, null)
//Result: 4

sumNumbers(4)
//Result: Uncaught Error: This  paramter is required

sumNumbers(4, undefined)
//Result: Uncaught Error: This  paramter is required

ES2018 new method “finally”

fetch(https://google.com).then((response) => {
console.log(response);
}).catch((error) => {
console.log(error)
})  // es2018 finally
.finally(() => {
//your code here
})

ES5 getters and setters

const user = {
firstName: "John",
lastName: "Doe"
}

//fullname is a virtual field
get fullName(){
return this.firstName + '' + this.lastName
},

//validate age before saving
set age(value) {
if(isNaN(value)) throw Error('Age must be a number')
this._age = Number(value)
},

// get age(){
return this._age
}

console.log(user.fullName) // John Doe
user.firstName = "vignes"
console.log(user.fullName) // vignes Doe
user.age = '25'
console.log(user.age) // 25
user.age ="Invalid text" // Error: Age must be a number

Multiple conditions in an IF statement

const status = 'online';

// Classical approach
if(status === 'online' || status === 'away' || status === 'busy'){
console.log('Do Something');
}

// A better approach
if(['online', 'away', 'busy'].indexOf(status) ! === -1) {
console.log('Do Something')
}

// Check indexOf with ~ operator
if(~['online', 'away', 'busy'].indexOf(status)){
console.log('Do Something')
}

// Even Better, using includes method => Favourite
if(['online', 'away', 'busy'].includes(status)){
console.log('Do Something')
}

Type coercion in Js
Type Coercion is the conversion of one type of object to a new object of a different type with similar content. Tapestry frequently must coerce objects from one type to another

console.log(false === 0) // true
console.log(true + false) // 1
console.log('val' + 40 + 60) // val4060
console.log(40 + 6 + 'val') // 46val
console.log('8' + 1) // 81
console.log('10' - 2) // 8
console.log(6 * null) // 0

ES6 startsWith() and endsWith()

const image ='hill-mountain.png';
const validImage = image.endsWith('.png');
// result: true

const hillMountain = 'Hill Mountain';
const startsWith = hillMountain.startsWith('Hill');
// result: true

Array.from()

The Array.from() methods crates a new shallowed copied array instance from an array or iterable object.

// Array from a string
Array.from('foo') 
//Result: ['f', 'o', 'o']

//Array form a set
const set = new Set(['foo', 'bar', 'baz', 'foo']);
Array.from(set);
// Result get unique value: ['foo', 'bar', 'baz'] 


//Array from a Map
const mapper = new Map([ ['1', 'a'], ['2', 'b'] ]);
Array.from(mapper.values())
// ['a', 'b']

Array.from(mapper.keys());
//['1' , '2']

Array form an Array-like object (arguments)
function f(){
return Array.from(arguments)
}

f(1,2,3) //result [1, 2, 3]

//Using an arrow function as the map function to manipulate the elements
Array.from([1,2,3], x => x + x) 
// result [2, 4 , 6]

entries() method

The entries() method returns a new Array Iterator object that contains the key/ value pairs for each index in the array

const arr = ['a', 'b', 'c']
const iterator = arr.entries()
console.log(iterator.next().value) 
// Result: Array [0, "a"]
console.log(iterator.next().value)
//Result: Array [1, 'b']

Array replacer by JSON.stringify()

const user = {
'username': 'helperscripter',
'email': 'help@helperscript.com',
'password': 'yourpassword'
}

const userString = JSON.stirngify(user, ['username', 'email']);
//result: 
{
'username': 'helperscripter',
'email': 'help@helperscript.com'
}

Javascript some() and Every() functions

const moneyHeist = [
{name : 'Denvar', age: '25'},
{name : 'Oslo', age: '40'},
{name : 'Tokyo', age: '17'}
]

moneyHeist.every(el => el.age > 18)
//return  false

moneyHiest.some(el => el.age < 18 )
//return true

I hope you all enjoy these methods and tricks. Thanks for reading. Please comment if it is useful.

< Javascript trick part 3

Top ten Javascript tricks part 3

Different ways to pass parameters to a setTimeout

const addNum = (a, b) => console.log(a + b); setTimeout(addNum, 1000, 2, 3) //result: 5 setTimeout(() => { addNum(2,3); },1000) //result: 5 setTimeout(addNum.bind(null, 2, 3), 1000); //result: 5

3 ways to get the Date and Time in milliseconds

new Date().getTime(); // 1576509862158 Date.now(); // 1576509862158 +new Date(); // 1576509862158

function() declaration in ES5 and ES6

// old way ES5
function tomAndJerry(){
}

// Es6
tomAndJerry() => {
}

Caching the array.length in the loop

let array = new Array(le9);

for(let i = 0; i < array.length; i++){
// this loop will calculate array length in each iteration
}

for(let i = 0; length =  array.length; i < array.length; i++){
// this loop will calculate array length only once
}

Different approaches to creating an HTML link

let myText = 'Click me please'

// usual way
`<a href="#">${myText}</a>`
// <a href="#">Click me please</a>

// Using link method
myText.link(#);
// <a href="#">Click me please</a>

Easily check the visibility of div or page

window.addEventListener('visiblitychange', ()=> {
// document => define any html element div, a, span
if(document.hidden){ 
console.log('div is hidden')
}else{
console.log('div is visible')
}
})

Check the data array or not? using isArray()

let array = [1,2,3,4]
let numb = 3

Array.isArray(array) // return true

Array.isArray(numb) // return false

Array.reduce()
It applies a function to each element in an array and reduces the array into a single element.

const arr = [5, 10, 15, 20, 25];

const result  = arr.reduce((total, currentValue) => {
console.log(currentValue); // 5 10 15 20 25
return total+currentValue;
});

console.log(result)
//result 75

How to verify that a given argument is a number

isNumber = (n) => {
return !isNaN(parseFloat(n)) isFinite(n);
}

isNumber(4) // true

isNumber(4.4) // true

isNumber('4') // false

Generate a random set of alphanumeric characters

// genreate random aplhanumeric
generateRandomAlphaNum = len =>{
var rdmString='';
for(; rdmString.length < len; rdmString += Math.random().toString(36).substr(2));
return rdmString.Substr(0, len);
}


generateRandomAlphaNum(5) // result blphj
generateRandomAlphaNum(11) // result: uug4th6ie2h
generateRandomAlphaNum(8) // result: rimbe38x

I hope this will help your developing skills. If any queries feel free in below comment section. Have a great day!.

< Javascript trick part 2 Javascript tirck part 4 >

Top Ten javascript tricks – part 2

Converting Object to Array – ES2017

// Converting Object => Array

const zoo = {
lion : 'animal',
peacock: 'bird'
}

//Keys
Object.keys(zoo)
// ['lion', 'parrot']

//values
Object.values(zoo)
// ['animal', 'bird']

//keys and values
Object.entries(zoo)
//[['lion','animal'], ['peacock','bird']]

Different ways to convert float to integer

Math.floor(5.95)
// 5

Math.ceil(5.15)
// 6

Math.round(5.4)
// 5

Math.round(5.5)
// 6

console.log(5.95 | 0); // quick way
//result: 5

Merging Object: Multiple objects into a single Object using the spread operator

const person= {name:'Jasim', gender:'Male'};
const tools ={computer:'Mac', editor:'VScode'};

const summary = {...person, ...tools};
*/
{
name: 'jasim',
gender:'Male',
computer:'Mac',
editor:'Vscode'
  }
/*

Make Console.log() output colorful and stylish in the browser console

console.log("%c I am red %c I am green", "color:red", "color:green" );
I am red I am green

Remove Character from String

let str ='Hello';

// remove first character
str.slice(1) // ello

// remove last character
string.substring(1,str.length -1)
// Hell

//remove substring from string
str.replace('ello', i)
// Hi

//remove character "LL" from "Hello" with split and join
str.split('l').join('')
// Heo

Add new element or push new element into an Array

let array = ['H', 'i'];

// add new element at last
array.push('!'); 
// ['H', 'i','!']

//add element at first
array.unShift('!')
// ['!','H', 'i']

3 ways to concat the multidimensional array

let nestedArray = [ [1, 2, 3], [4, 5], [6, 7,8]];

//using Array.flat() method
nestedArray.flat()
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat and apply
[].concat.apply([], nestedArray)
//result : [1, 2, 3, 4, 5, 6, 7, 8]

//usign concat with ...spread operator
[].concat(...nestedArray);
//result : [1, 2, 3, 4, 5, 6, 7, 8]

Naming Conventional

//Camel case => mostly for variable declaration (camelCase)

<p id="camelCase>Hello!</p>
var camelCase;

//Pascal case (PascalCase)
class PascalCase{}

//hyphen html attribute declaration
<p class="main-paragraph">Hello1</p>

Array sort()

let array = [40, 2, 3, 45, 25, 100]

//Old way
array.sort(function(a, b){ return a-b});
// [2, 3, 25, 40, 45, 100]

//New Es6 way
array.sort((a,b) => a - b)
// [2, 3, 25, 40, 45, 100]

Change the color of cursor (caret) – CSS

input {
caret-color: auto
}

input{
caret-color: red
}
// text the color of below input caret cursor

I hope you enjoying this beautiful tricks in javascript. The third part of the javascript tricks in the next article.

< Part 1 javascript trick

Part 3 javascript trick >