Monday, July 5, 2021

Javascript tips and tricks

 Tips & Tricks


1. Abonden the bootstrap

https://betterprogramming.pub/3-reasons-to-abandon-bootstrap-in-2021-aa71bbc1af14


1. Conditionally Add Properties to Object

const condition = true;

const person = {

  id: 1,

  name: 'John Doe',

  ...(condition && { age: 16 }),

};




4. The Keyword in

const user = {

  name: "Mehdi",

  age: 19,

}

if("age" in user){

  console.log("Age is available in the user object.");

}

//Age is available in the user object.

"name" in user; //true

"text" in user; //false

if("text" in user){

  console.log("text is available");

}

//undefined.

5. Nullish Coalescing, ?? Operator

const foo = null ?? 'Hello';

console.log(foo); // returns 'Hello'

const bar = 'Not null' ?? 'Hello';

console.log(bar); // returns 'Not null'

const baz = 0 ?? 'Hello';

console.log(baz); // returns 0

with OR

const cannotBeZero = 0 || 5;

console.log(cannotBeZero); // returns 5

const canBeZero = 0 ?? 5;

console.log(canBeZero); // returns 0

9. Check Falsy Values in an Array

const myArray = [null, false, 'Hello', undefined, 0];

// filter falsy values

const filtered = myArray.filter(Boolean);

console.log(filtered); // returns ['Hello']

// check if at least one value is truthy

const anyTruthy = myArray.some(Boolean);

console.log(anyTruthy); // returns true

// check if all values are truthy

const allTruthy = myArray.every(Boolean);

console.log(allTruthy); // returns false


5. Dynamic properties

const dynamic = 'name'

const person = {

    age: 33,

    [dynamic]: 'John'

}


const dynamic = 'name'

const person = {

    age: 33,

    [dynamic]: 'John',

    [`interpolated-${dynamic}`]: true

}

const dynamic = 'name'

let person = {

    age: 33,

}

person[dynamic] = 'John'




8. Unique array values

const numbers = [1, 2, 2, 3, 3, 4, 5, 5, 6, 6, 7, 7, 7]

const unique_numbers = [...new Set(numbers)]

console.log(unique_numbers); // [1, 2, 3, 4, 5, 6, 7]




No comments: