Notice
Recent Posts
Recent Comments
Link
일 | 월 | 화 | 수 | 목 | 금 | 토 |
---|---|---|---|---|---|---|
1 | 2 | |||||
3 | 4 | 5 | 6 | 7 | 8 | 9 |
10 | 11 | 12 | 13 | 14 | 15 | 16 |
17 | 18 | 19 | 20 | 21 | 22 | 23 |
24 | 25 | 26 | 27 | 28 | 29 | 30 |
Tags
- sonoff
- open cursors
- EXK
- tvheadend
- angular 6
- Data Transfer Object(DTO)
- 자바개발
- 프로젝트관리
- CBD 단점
- maven #junit
- 객체설계
- 네트워크 기본개념
- ASUS 공유기
- 소프트웨어설계
- docker 네트워크
- Value Object(VO)
- Tomcat error-page version
- 구글캘린더 검색
- LG그램2017
- LAN WAN
- USB-C충전
- 자바튜닝
- SW설계
- SW분석
- 실해하지 않는
- 자바스크립트 JQuery
- 경력개발자
- SpringBoot
- SI와 SM 차이점
- USB-C to HDMI 아답터
Archives
- Today
- Total
대빵's Blog
자바스크립트 코드 개선 기술 본문
Tenary Operator (삼항연산자)
```
///////////////// 삼항연산자 //////////////
// bad code
function getResult1(score) {
let result;
if (score > 5) {
result = '👍';
} else {
result = '👎';
}
return result;
}
// good code
function getResult2(score) {
return score > 5 ? '👍' : '👎';
}
console.log(getResult1(5));
console.log(getResult2(5));
```
Nullish Coalescing Operator
```
///////////////// Nullish Coalescing Operator //////////////
// bad code
function printMessage1(text) {
let message = text;
if (text == null || text == undefined) {
message = 'Nothing to display';
}
console.log(message);
}
// good code
function printMessage2(text) {
const message = text ?? 'Nothing to display'
console.log(message);
}
// cf : default parameter 를 사용하는 경우 null 처리가 안됨.
function printMessage3(text = 'Nothing to display') {
console.log(text);
}
// cf : logical OR Operator => leftExpr(falsy) || rightExpr
function printMessage4(text) {
// falsy => false, 0, -0, NaN, undefined, null, '', "", ``
const message = text || 'Nothing to display'
console.log(message);
}
/*
const result = getInitialState() ?? fetchFromServer();
console.log(result);
function getInitialState() {
return null;
}
function fetchFromServer() {
return 'Hiya from ';
}
*/
printMessage2('Hello');
printMessage2(undefined);
printMessage2(null);
printMessage3('Hello');
printMessage3(undefined);
printMessage3(null);
printMessage4('Hello');
printMessage4(undefined);
printMessage4(null);
printMessage4(0);
printMessage4('');
```
Object Destructuring
```
// Object Destructuring
const person = {
name: 'Julia',
age: 30,
phone: '01077777777'
};
// bad code
function displayPerson(person) {
displayAvatar(person.name);
displayName(person.name);
displayProfile(person.name, person.age);
}
// good code
function displayPerson(person) {
const { name, age } = person;
displayAvatar(name);
displayName(name);
displayProfile(name, age);
}
```
Object & Array Spread
```
// Spread object and array
const item = { type: '👔', size: 'M' };
const detail = { price: 20, made: 'Korea', gender: 'M' };
// bad code
const newObject = new Object();
newObject['type'] = item.type;
newObject['size'] = item.size;
newObject['price'] = item.price;
newObject['made'] = item.made;
newObject['gender'] = item.gender;
// good code
const shirt0 = Object.assign(item, detail);
const shirt = { ...item, ...detail };
const shirt = { ...item, ...detail, price: 40 }; // deatil 의 price 만 40 으로 변경
// spread syntax - array
let fruites = ['🍉', '🍊', '🍌']
// fruits.push('🍓')
fruits = [...fruites, '🍓']
// fruits.unshift('🍇')
fruits = ['🍇', ...fruites]
const fruits2 = ['🍉', '🍊', '🍌'];
let combined = fruits.concat(fruits2);
combined = [...fruits, ... fruits2];
```
Optional Chaining
```
// Optional chaining
const bob = {
name: 'Julia',
age: 20,
};
const anna = {
name: 'Julia',
age: 20,
job: {
title: 'Software Engineer'
},
};
// bad code
function displayJobTitle(person) {
if (person.job && person.job.title) {
console.log(person.job.title);
}
}
// good code
function displayJobTitle(person) {
if (person.job?.title) {
console.log(person.job.title);
}
}
function displayJobTitle(person) {
const title = persion.job?.title ?? 'No Job Yet';
console.log(title);
}
```
Template literals
```
// Template Literals (Template String)
const person = {
name: 'Julia',
score: 4,
};
// bad code
console.log ( 'Hello' + person.name + ', Your current score is:' + person.score);
// good code
console.log(`Hello ${person.name}, Your current score is: ${person.score}`);
// good code
const { name, score } = person;
console.log(`Hello ${name}, Your current score is: ${score}`);
// good code
function greetings(person) {
const { name, score } = person;
console.log(`Hello ${name}, Your current score is: ${score}`);
}
```
Loops
```
// Looping - Q : 짝수들만 각각 4를 곱한 전체합
const items = [1,2,3,4,5,6]
// bad code
const evens = getAllEvens(items);
const multiple = multiplyByFour(evens);
const sum = sumArray(multiple);
console.log(sum);
function getAllEvens(items) {
const result = [];
for (let i=0, j=items.length ; i<j ; i++) {
if (items[i] % 2 === 0) {
result.push(items[i]);
}
}
return result;
}
function multiplyByFour(items) {
const result = [];
for (let i=0, j=items.length ; i<j ; i++) {
result.push(items[i] * 4);
}
return result;
}
function sumArray(items) {
let sum = 0;
for (let i=0 , j=items.length ; i<j ; i++) {
sum += items[i];
}
return sum;
}
// good code
function getAllEvens(items) {
return items.filter(num => num % 2 === 0);
}
function multiplyByFour(items) {
return items.map(num => num * 4);
}
function sumArray(items) {
return items.reduce((a, b) => a + b, 0);
}
// good code final 1
const evens = items.filter((num) => num % 2 === 0);
const multiple = evens.map((num) => num * 4);
const sum = multiple.reduce((a,b) => a + b, 0);
console.log(sum);
// good code final 2
const result = items
.filter((num) => num % 2 === 0)
.map((num) => num * 4)
.reduce((a,b) => a + b, 0);
console.log(result);
```
Async (promise 대체)
```
// Promise -> Async/await
// bad code
function displayUser() {
fetchUser()
.then((user) => {
fetchProfile(user)
.then((profile) => {
updateUI(user, profile);
});
});
}
// good code
async function displayUser() {
const user = await fetchUser();
const profile = await fetchProfile(user);
updateUI(user, profile);
}
```
Remove Duplicate 방법
```
// Remove Duplicates
const array = ['🐶', '🐱', '🐂', '🐱', '🐈', '🐶']
console.log(array);
// 중복제거
console.log([...new Set(array)]);
```
'개발관련' 카테고리의 다른 글
gradle dependencies 확인하기 (0) | 2022.04.17 |
---|---|
gradle executable jar 만들기 (0) | 2021.12.07 |
SourceTree(Atlassian) with WSL(SourceTree 에서 WSL 소스보기) (0) | 2021.03.31 |
소프트웨어 버그와 에러의 구분이 필요한 이유(주관적인 관점으로...) (0) | 2021.03.06 |
윈도우 이클립스 Maven 속도향상 (0) | 2020.03.16 |