Optional Chaining

let book = {
  name: "Harry Potter 1",
  weight: {
    version1: {
      value: 550,
      unit: 'g'
    },
  }
}

console.log(book?.weight?.version2?.value);
//690

console.log(book?.weight?.version3?.value);
//undefined
// does not throw an error trying to access an undefined property

Throttling & Debounding

Throttling - enforces a maximum number of times a function can be called over time. As in “execute this function at most once every 100 milliseconds.

Debouncing - enforces that a function not be called again until a certain amount of time has passed without it being called. As in “execute this function only if 100 milliseconds have passed without it being called.

Convert string to number

let string = +"1";

// String
console.log(typeof string);

Shorthand JS

Ternary Operator

const x = 20;
const answerText = x > 10 ? "greater than 10" : "less than 10";

For Loop

const fruits = ['mango', 'peach', 'banana'];

for(index in fruits) {
  console.log(index, fruits[index]);
}

Short-circuit Evaluation

let name;
if (data.name) {
  name = data.name;
} else {
  name = 'Unknown';
}

// Shorthand
const name = data.name || 'Unknown';

Object Property Shorthand

const name = 'Shane', age = 33;
const obj = { x:x, y:y };

// Shorthand
const obj = {x, y};

KeyCode values

Enter = 19
Escape = 27
Tab = 9

keycode.info

Convert a string to boolean

const isTrue = (theValue == 'true');

slideUp/slideDown with JS

const slideUp = (target, duration = 500) => {
    target.style.transitionProperty = 'height, margin, padding';
    target.style.transitionDuration = duration + 'ms';
    target.style.boxSizing = 'border-box';
    target.style.height = target.offsetHeight + 'px';
    target.offsetHeight;
    target.style.overflow = 'hidden';
    target.style.height = 0;
    target.style.paddingTop = 0;
    target.style.paddingBottom = 0;
    target.style.marginTop = 0;
    target.style.marginBottom = 0;
    window.setTimeout(() => {
        target.style.display = 'none';
        target.style.removeProperty('height');
        target.style.removeProperty('padding-top');
        target.style.removeProperty('padding-bottom');
        target.style.removeProperty('margin-top');
        target.style.removeProperty('margin-bottom');
        target.style.removeProperty('overflow');
        target.style.removeProperty('transition-duration');
        target.style.removeProperty('transition-property');
        //alert("!");
    }, duration);
}

const slideDown = (target, duration = 500) => {
    target.style.removeProperty('display');
    let display = window.getComputedStyle(target).display;

    if (display === 'none')
        display = 'block';

    target.style.display = display;
    let height = target.offsetHeight;
    target.style.overflow = 'hidden';
    target.style.height = 0;
    target.style.paddingTop = 0;
    target.style.paddingBottom = 0;
    target.style.marginTop = 0;
    target.style.marginBottom = 0;
    target.offsetHeight;
    target.style.boxSizing = 'border-box';
    target.style.transitionProperty = "height, margin, padding";
    target.style.transitionDuration = duration + 'ms';
    target.style.height = height + 'px';
    target.style.removeProperty('padding-top');
    target.style.removeProperty('padding-bottom');
    target.style.removeProperty('margin-top');
    target.style.removeProperty('margin-bottom');
    window.setTimeout(() => {
        target.style.removeProperty('height');
        target.style.removeProperty('overflow');
        target.style.removeProperty('transition-duration');
        target.style.removeProperty('transition-property');
    }, duration);
}

const slideToggle = (target, duration = 500) => {
    if (window.getComputedStyle(target).display === 'none') {
        return slideDown(target, duration);
    } else {
        return slideUp(target, duration);
    }
}

Sort Alphabetically

const arr = ['b', 'c', 'a'];
arr.sort();
// ['a', 'b', 'c']

The 'new' operator

  • It creates a new, empty object.
  • It binds this to our newly created object.
  • It adds a property onto our newly created object called “__proto__” which points to the constructor function’s prototype object.
  • It adds a return this to the end of the function, so that the object that is created is returned from the function.

Clone an array

const array = [1,2,3,4,5];

const a = [...array];
const b = array.slice();

Slice & Splice

splice() method changes the original array where as slice() doesn't change the original array and infact returns a new one.

Slice() creates a new array object with the extracted portion

var names = ['Joe', 'Paul', 'Shane', 'Tom', 'Ralph'];

console.log(animals.slice(2));
// ["Shane", "Tom", "Ralph"]

console.log(animals.slice(0,2));
// ["Joe", "Paul"]

Splice() changes the contents of an array by removing existing elements and/or adding new elements.

names.splice(1, 0, 'Carol');
console.log(names);
// ['Joe', 'Carol', 'Paul', 'Shane', 'Tom', 'Ralph'];

names.splice(0, 4, 'June');
console.log(names);
// ['June', 'Ralph'];

JSON to string

// JSON to string
JSON.stringify({x: 5, y: 6});

// String to JSON
const str = "{ hello: 'world', places: ['Africa', 'America', 'Asia', 'Australia'] }"
JSON.stringify(eval('('+str+')'));

// OR, if the JSON defo correct
JSON.parse(jsontext);

Is not undefined

// to check if a variable is declared and is not undefined
if (typeof yourvar !== 'undefined')

// Does not execute if yourvar is `undefined`
if (yourvar === null)

// If know the variable exists, and want to check whether there's any value stored in it
if (yourvar !== undefined)

// If is true, or false
if (yourvar)
if (!yourvar)

Mobile swipe

document.addEventListener('touchstart', handleTouchStart, false);        
document.addEventListener('touchmove', handleTouchMove, false);

var xDown = null;                                                        
var yDown = null;                                                        

function handleTouchStart(evt) {                                         
    xDown = evt.touches[0].clientX;                                      
    yDown = evt.touches[0].clientY;                                      
};                                                

function handleTouchMove(evt) {
    if ( ! xDown || ! yDown ) {
        return;
    }

    var xUp = evt.touches[0].clientX;                                    
    var yUp = evt.touches[0].clientY;

    var xDiff = xDown - xUp;
    var yDiff = yDown - yUp;

    if ( Math.abs( xDiff ) > Math.abs( yDiff ) ) {/*most significant*/
        if ( xDiff > 0 ) {
            /* left swipe */ 
        } else {
            /* right swipe */
        }                       
    } else {
        if ( yDiff > 0 ) {
            /* up swipe */ 
        } else { 
            /* down swipe */
        }                                                                 
    }
    /* reset values */
    xDown = null;
    yDown = null;                                             
};

Stackoverflow - givanse

Get Day

var d = new Date();
console.log(d);

var c = new Date('1964-03-30T16:43:40.723Z');
var days = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
console.log(days[c.getDay()]);

Get CSS values in JS

Inline styles

<div class="el" style="font-size: 2em; color: red;">1234</div>
const element = document.querySelector('.element')

const fontSize = element.style.fontSize
console.log(fontSize) // 2em

const color = element.style.color
console.log(color) // red

From a stylesheet

const style = getComputedStyle(element)

getComputedStyle is read-only. You cannot set a CSS value with getComputedStyle unlike inline styles

From pseudo elements

.element::before { content: "Before pseudo element"; }
pseudoElementStyle = getComputedStyle(element, '::before')