2020년 12월 7일 월요일

JavaScript Tricks

 

1. Convert string to number

the_string = "123";
console.log(+the_string);
// 123

the_string = "hello";
console.log(+the_string);
// NaN

2. Convert a number to a string

var converted_number = 5 + "";
console.log(converted_number);
// 5
console.log(typeof converted_number);
// string

3. Extract Unique Values

var entries = [1, 2, 2, 3, 4, 5, 6, 6, 7, 7, 8, 4, 2, 1]
var unique_entries = [...new Set(entries)];
console.log(unique_entries);
// [1, 2, 3, 4, 5, 6, 7, 8]

4. Flatten a multidimensional array

var entries = [1, [2, 5], [6, 7], 9];
var flat_entries = [].concat(...entries);
// [1, 2, 5, 6, 7, 9]

5. Replace All

var example = "potato potato";
console.log(example.replace(/pot/, "tom")); 
// "tomato potato"
console.log(example.replace(/pot/g, "tom")); 
// "tomato tomato"

6. Short Circuit Conditionals

if (available) {
addToCart();
}
available && addToCart()

7. Use the length to resize and empty an array

var entries = [1, 2, 3, 4, 5, 6, 7];  
console.log(entries.length);
// 7
entries.length = 4;
console.log(entries.length);
// 4
console.log(entries);
// [1, 2, 3, 4]
var entries = [1, 2, 3, 4, 5, 6, 7]; 
console.log(entries.length);
// 7
entries.length = 0;
console.log(entries.length);
// 0
console.log(entries);
// []

8. Shuffle elements from array

var my_list = [1, 2, 3, 4, 5, 6, 7, 8, 9];
console.log(my_list.sort(function() {
return Math.random() - 0.5
}));
// [4, 8, 2, 9, 1, 3, 6, 5, 7]

9. Dynamic Property Names

const dynamic = 'flavour';
var item = {
name: 'Coke',
[dynamic]: 'Cherry'
}
console.log(item);
// { name: "Coke", flavour: "Cherry" }

10. Object values

JavaScript has also introduced the Object.values that returns a single dimension array of the object values.

Have a look at the example below:

const person = {
firstName : "Mehdi",
lastName : "Aoussiad",
age : 19,
eyeColor : "black"
};
console.log(Object.values(person));
// Prints ["Mehdi","Aoussiad",19,"black"]

11. Object entries

The Object.entries are similar to Object.values, but returns a multi-dimension array of the object values and properties(keys).

Here is an example:

const person = {
firstName : "Mehdi",
lastName : "Aoussiad",
age : 19,
eyeColor : "black"
};
console.log(Object.entries(person));
// Prints: [["firstName", "Mehdi"],["lastName", "Aoussiad"],["age", 19],["eyeColor", "black"]]

12. Get the last element of an array
let numbersArr = [4, 8, 9, 34, 100];numbersArr[numbersArr.length - 1]; //return 100// 혹은numbersArr.slice(-1)[0];

13. Random number in a specific range



As you know, we use the method Math.random() to return a random number between 0 and 1.
// Random number between 0 and 4.
Math.floor(Math.random() * 5);
// Random number between 0 and 49.
Math.floor(Math.random() * 50);
// Random number between 0 and 309.
Math.floor(Math.random() * 310);


14. Flattening multi-dimensional array
let arr = [5, [1, 2], [4, 8]];arr.flat(); //returns [5, 1, 2, 4, 8]let twoLevelArr = [4, ["John", 7, [5, 9]]]twoLevelArr.flat(2); //returns [4, "John", 7, 5, 9]


15. Check for multiple conditions

let name = "John";//Bad way.
if(name === "John" || name === "Ben" || name === "Chris"){
console.log("included")
}
//Better way.
if(["John", "Ben", "Chris"].includes(name)){
console.log("included")
}


16. Extract unique values


const languages = ['JavaScript', 'Python', 'Python', 'JavaScript', 'HTML', 'Python'];const uniqueLanguages = [...new Set(languages)];
console.log(uniqueLanguages);
//prints: ["JavaScript", "Python", "HTML"]

17. Run an event only once


If you have an event that you want to only run once, you can use the option once as a third parameter for addEventListener() .

Here is the example:

document.body.addEventListener('click', () => {
console.log('Run only once');
}, { once: true });

As you can see, you just have to set the option to true and the event will only run once.

18. Sum all numbers in an array


let numbers = [6, 9 , 90, 120, 55];numbers.reduce((a, b)=> a + b, 0); //returns 280

19. Sum numbers inside an array of objects

const users  = [
{name: "John", age: 25},
{name: "Chris", age: 20},
{name: "James", age: 31},
]

users.reduce(function(a, b){
return {age: a.age + b.age}
}).age;

20. The keyword “in”


Use the keyword in in JavaScript to check if properties are defined inside an object or if elements are included inside an array for example.
const employee = {
name: "Chris",
age: 25
}
"name" in employee; //returns true.
"age" in employee; //returns true.
"experience" in employee; //retuens false.



21. From number to an array of digits

const toArray = num => [...`${num}`].map(elem=> parseInt(elem))
// 위 구문의 다른 방법// const toArray = num => String(num).split("").map(el=> +el);toArray(1234); //returns [1, 2, 3, 4]
toArray(758999); //returns [7, 5, 8, 9, 9, 9]

Null, undefined and empty checks shorthand

JavaScript multiple conditions shorthand

JavaScript loops shorthand

JavaScript implicit return shorthand

JavaScript spread operator shorthand

JavaScript arrow function shorthand

JavaScript template literals shorthand

JavaScript multi-line string shorthand

JavaScript Array.find shorthand


댓글 없음:

댓글 쓰기