javascript 깨끗한 코드로 쓰자!

정혜윤·2021년 11월 21일
0

javascript

목록 보기
2/2
post-thumbnail

Ternary Operator

// Bad Code
function getResult(score) {
	let result;
    if (score > 5) {
    	result = 'up';
    } else if (score <= 5) {
    	result = 'down';
    }
    return result;
}

// Good Code 
function getResult(score) {
	return result > 5 ? 'up' : 'down';
}

Nullish Coalescing Operator

// Bad Code 
function printMessage(text) {
	let message = text;
    if (text == null || text == undefined) {
    	message = 'Nothing to display';
    }
    console.log(message);
}

// Good Code 
function printMessage(text) {
	const message = text ?? 'Nothing to display';
    console.log(message);
}

// Default parameter is only for undefined 
function printMessage(text = 'Nothing to display') {
    console.log(message); // null 은 그대로 null 노출 
}
// ex
function getInitialState() {
	return null;
}

function fetchFromServer() {
	return 'hiya from korea';
}

const result = getInitialState() ?? fetchFromServer();
console.log(result); // 'hiya from korea';

Nullish Coalescing Operator vs Default parameter

Nullish Coalescing Operator - undefined, null check 
Default parameter - only undefined check 

Nullish coalescing operator ?? vs Logical OR operator ||

leftExpr ?? rightExpr
leftExpr = null, undefined
leftExpr || rightExpr
leftExpr = falsy - null, undefined, false, 0, -0, '', "", ``

Object Destructuring

const person = {
	name: 'jhyounyaho',
    age: 31,
    phone: '01000000000',
}

// Bad Code
function displayPerson(person) {
	displayAvatar(person.name);
    displayName(person.name);
    displayProfile(person.name, person.age);
}

// Bad Code 
function displayPerson(person) {
	const name = person.name;
    const age = person.age;
	displayAvatar(name);
    displayName(name);
    displayProfile(name, age);
}

// Good Code 
function displayPerson(person) {
	const { name, age } = person;
	displayAvatar(name);
    displayName(name);
    displayProfile(name, age);
}

Spread Syntax

// Spread Syntax - Object 
const item = { type: 'shirts', size: 'M };
const detail = { price: 20, made: 'Korea', gender: 'M'};

// Bad Code 원본 배열을 직접적으로 수정 
item['price'] = detail.price; 

// Bad Code 수동적으로 할당 
const newObject = new Object();
newObject['type'] = item.type;
newObject['size'] = item.size;
newObject['price'] = detail.price;
newObject['made'] = detail.made;
newObject['gender'] = detail.gender;

// Bad Code  수동적으로 할당 
const newObject2 = {
	type: item.type,
    size: item.size,
    price: detail.price,
    made: detail.made,
    gender: detail.gender,
}

// Good Code 예전 문법 
const shirt0 = Object.assign(item, detail);

// Good Code 
let combined = item.concat(detail);

// Beeter Code - object, array 둘 다 가능 
const shirt = { ...item, ...detail };

// tip - spread syntax 는 기존 값을 유지하면서 특정 값만 업데이트 할 수 있다. 
const shirt2 = { ...item, ...detail, price: 40 };

// Spread Syntax - Array 
let fruits = ['apple', 'banana', 'orange'];

// fruits.push('lemon');
fruits = [...fruits, 'lemon'];

// fruits.pop('peach');
fruits = ['peach', ...fruits];

Optional Chaining

// Optional Chaining
const jhyounyaho = {
	name: 'jhy',
    age: 31,
};

const buzzy = {
	name: 'buzzylight',
    age: 30,
    job: {
    	title: 'frontend developer',
    },
};


// Bad Code
function displayJobTitle(person) {
	if (person.job && person.job.title) {
    	console.log(person.job.title);
    }
}

// Good Code 
function displayJobTitle(person) {
 	// person.job 이 있다면, 그 안에 있는 title이 있는지 없는지 확인 
	if (person.job?.title) {
    	console.log(person.job.title);
    }
}

// Good Code 
function displayJobTitle(person) {
	// person.job && person.job.title 있다면, person.job title 출력 
    // 없다면 No Job Yet 출력 
	const title = person.job?title ?? 'No Job Yet';
    console.log(title);
}

Template Literals (Template String)

const person = {
	name: 'jhyounyaho',
    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.name}`);

// Good Code
function greetings(person) {
	const { name, score } = person;
	console.log(`Hello ${name} Your current score is: ${name}`);
}

Loops

const items = [1, 2, 3, 4, 5, 6];

짝수인 경우 4로 곱해서 총합을 구하기

// Bad Code 
function getAllEvens(items) {
	return items.fileter(num => num % 2 === 0)
}

function multiplyByFour(items) {
	return items.map(num => num * 4);
}

function sumArray(items) {
	items.reduce((a, b) => a + b, 0);
}

const evens = getAllEvens(items);
const multiple = multiplyByFor(evens);
const sum = sumArray(multiple);
console.log(sum);

// Good Code
function totalSum(items) { 
	const evens = items.filter(num => num % 2 === 0);
	const multiple = evens.map(num => num * 4);
	const sum = multiple.reduce((a, b) => a + b, 0);
	return sum; 
}

// Good Code
function totalSum(items) { 
	const total = items
    	.filter(num => num % 2 === 0)
		.map(num => num * 4);
		.reduce((a, b) => a + b, 0);
	return total; 
}

// 내 코드 
function totalSum(items) {
	let total = 0;
	for (let i in items) {
		if (items[i] % 2 == 0) {
    		total += items[i] * 4;
    	}
	}
    return total;
}

async, await

// Promise -> async/await 

// Bad Code 
function displayUser() {
	fetchUser() 
    	.then((user) => {
        	fetchProfile(user)
            	.then((profile => (parameter) 
                	updateUI(user, profile);
                });
        });
}

// Good Code
async function displayUser() {
	const user = await fetchUser();
    const profile = await fetchProfile();
    updateUI(user, profile);
}

Remove Duplicates

// 배열은 중복을 허용 
const array = ['A', 'B', 'C', 'A', 'E', 'B'];

// Good Code 
// Set 은 중복을 허용하지 않음. 
console.log([...new Set(array)]);

출처

https://youtu.be/BUAhpB3FmS4
자바스크립트 프로처럼 쓰는 팁 ✨ (+ 보너스 인터뷰 문제 하나!) - 드림코딩 by 엘리

profile
frontend developer

0개의 댓글