JS - Other

Short Conditionals

//true condition
if(A == A) && console.log(); 

//false condition
if(A != A) || console.log(); 

Should async/await functions be added with try catch?

There is no need to interrupt when an exception occurs at await. You can write it like this. You need to do a non-null check and the console will not report an error message.

let userInfo = await getUserInfo().catch(e => console.warn(e))
if (!userInfo) return


If you need to interrupt when an exception occurs at await and care about console errors, you can write

try { 
  let userInfo = await getUserInfo() 
  let pageInfo = await getPageInfo(userInfo?.userId) 
} catch(e) { 
  console.warn(e) 
}


If you need to interrupt when an exception occurs at await, but don't care about console errors, you can write it like this

let userInfo = await getUserInfo().catch(e => {
    console.warn(e)
    return Promise.reject(e)
})

let pageInfo = await getPageInfo(userInfo?.userId)

Shuffle Elements From Array

array.sort(function(){
  return Math.random() - 0.5
}}};

Sorting Of Integer Array

Ascending Order

Array.sort(function(a, b){return a-b});


Descending Order

Array.sort(function(a, b){return b-a});

Sorting Of String Array

Ascending Order

Array.sort();


Descending Order

Array.sort().reverse();

Sum all Numbers in an Array

array.reduce((a, b) => a + b, 0);

Swap Variable

[var1, var2] = [var2, var1];

Template Literals

db = 'http://${host}:${port}/${database}';

Tracker In JavaScript

index.html

<div class="tracker">
<div>


style.css

.tracker {
  position: fixed;
  transform: translate (-50%, -50%);
  width: 40px;
  z-index: 9999;
  pointer-events: none;
  transition: all .15s;
}

.tracker svg {
  width: 100%;
  height: 100%;
}


app.js

const tracker = document.queryselector(".tracker");
document.body.addEventListener("mousemove", e => {
  tracker.style.left = `${e.clientX}px`;
  tracker.style.top = '${e.clientY}px`;
});

Truncate Number

toFixed = (n, fixed) => ~~(Math.pow(10, fixed) * n) / Math.pow(10, fixed);

Uncheck checked radio button by clicking on label

$("input:radio + label").click(function () {
    this.previousElementSibling.click();
});

Using Modules for Code Organization

// greetings.js
export function greet(name) {
  console.log('Hello, ' + name + '!');
}

// calculations.js
export function calculateSquare(num) {
  return num * num;
}

// main.js
import { greet } from './greetings';
import { calculateSquare } from './calculations';
greet('Alice');
console.log(calculateSquare(3));