JavaScript tips and tricks

JavaScript tips and tricks

assigning values to multiple variable

let [one,two,three,four] = [1,2,3,4]

short circuit evaluation

const a = true
const go=()=>console.log('nice')

// long hand
if(a){
go();
}

// short hand
a && go();

swap two variables

[a,b] = [b,a]

multiple condition checking

//long hand 

if(value===1||value===2|| value ===3){
//do stuff
}

//short hand
if([1,2,3].include(value){
// do stuff
}

object property assignement

let firstName=marwen
let lastName=labidi
//long hand 
const o={
firstName:firstName,
lastName:lastName

}

//short hand
const o={
firstName,
lastName
}

string into a number

let string =`555`
let number=+s

number into a string

let number=555
let string=number+``

repeating a string for multiple time

const string=`hello`
string.repeat('5');

power

const p=5**2 // 25

bitwise operator

const n=5.00034
console.log(~~n) // 5

mergin array

const arr1=[1,2,3,4]
const arr2=[5,6,7,8]

const arrMerg=[...arr1,...arr2]

copying

// don't work if there is nesting 
const arr1=[1,2,3,4]
const copyarr=[...arr1]

//don't work if there is a function , udefined ,nan or date value

const arr =[1,2,3,[3,4],[[55,5544],[4,5]]]
const copyarr=Json.parse(Json.stringify(arr))

// work with everything
use `cloneDeep()` methode in `loadsh` library

run event listener only once

button.addEventListener('click',()=>{},{once:true})

empty array in one line

arr.length=0

shuffle an array

arr.sort(()=>Math.random-0.5)

check if an object is empty

const o={}

Object.entries(o).length===0 // true

filter duplicate values from array

const arr=[3,3,3,3,3]

const result=[... new Set(arr)]

remove falsy values from array

const arr=[false,undefined,4,4,0,null]

arr.filter(()=>Boolean) // [4,4]

convert any value to boolean

!! string //true
!! 0 //false
!! null  //false
!! 5 //true

resizing array

// use length property
const arr=[1,3,3,4,4]
arr.length(1)//[1]

flatten multidimensional array

//use `.flat()` methode
const arr=[1,2,3,4,[[[4]]]]
 arr.flat(infinity)

replace all occurrence of a string

// use replace.All() methode

log value with variable name

let name=marwen
console.log({marwen}) // {name:marwen}

check performance of any task

const t1=performance.now()
//code
const t2=performance.now()
console.log(t1-t2)

check not a number

// use `isNaN()` methode

global this

// `globalThis` replace this and self and windows in the same time

.at() methode

const arr=[1,2,3,4,5]

arr.at(-2)//4

optional chaining

const o={}
o.address // error 
o?.address // undefined

logical multiassignement

// assing a varriable only if its not defined
let a 
a??=44 
let b=77
b??=100 // b=77 not working the seconde assignement

logical assignment

//  ||= assing a value already falsy
let x=0
x||=2 // x=2


// &&= assign a value already truthy
let x=0
x&&=2 // x=0 not working