Last active
December 3, 2022 18:04
-
-
Save Khant-Nyar/5808e0d9f1631d7075b6025de193b3ce to your computer and use it in GitHub Desktop.
tips and tracks in javascript
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
//1. Destructuring with Parameters | |
buttonElement.addEventListener("click", ({ target }) { | |
// is the same as using e.target 👇 | |
console.log(target); | |
}); | |
//Old Code (using if statement - 4 lines) | |
let username = getUsername(); | |
if (!username) { | |
username = "Dom"; | |
} | |
//New Code (using || - 1 line) | |
const username = getUsername() || "Dom"; | |
//advanced array search | |
const occupations = [ | |
"Lawyer", | |
"Doctor", | |
"Programmer", | |
"Chef", | |
"Store Manager", | |
]; | |
const result = occupations.find(o => o.startsWith("C")); | |
// "Chef" 🧑🍳 | |
console.log(result); | |
//remove dupclite from array | |
const numbers = [5, 10, 5, 20]; | |
const withoutDuplicates = Array.from(new Set(numbers)); | |
// [5, 10, 20] 👇 | |
console.log(withoutDuplicates); | |
// Self-Invoking Functions | |
const someComplexValue = (() => { | |
const a = 10; | |
const b = 20; | |
if (a > b) { | |
return a * b; | |
} | |
return b / a; | |
})(); | |
1. Turn an If…Else to a One-Liner | |
Commonly if-else statements look like this: | |
if (1 < 2) { | |
console.log("True."); | |
} else { | |
console.log("False"); | |
} | |
But there is a neater way to achieve the same with a ternary operator: | |
1 < 2 ? console.log("True.") : console.log("False."); | |
if(data && data.test){ | |
console.log(data.test.value); | |
} | |
Luckily, with optional chaining, you are able to write the above more simply by: | |
console.log(data?.test?.value); | |
let visitor; | |
let person; | |
visitor = 'Doe'; | |
person = visitor ?? 'staff'; | |
// person: Doe | |
visitor = null; | |
person = visitor ?? 'staff'; | |
// person: staff |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment