프론트엔드/Javascript

[Javascript] 유용하게 쓸 수 있는 기술 몇 가지

earthssu 2021. 4. 9. 17:25

Javascript에서 몇 가지의 테크닉을 통해 개발 시간을 줄일 수 있다.

뿐만 아니라 가독성 또한 올라가니 손에 익혀두고 유용하게 사용해보자!

 

출처 : js.plainenglish.io/20-javascript-shorthand-techniques-that-will-save-your-time-f1671aab405f

 

20 JavaScript Shorthand Techniques that will save your time

The shorthand techniques of any programming language help you to write more clean and optimized code. Shorthand techniques improve…

javascript.plainenglish.io

 

삼항 연산자

let result = marks >= 30 ? 'Pass' : 'Fail';

기본값 할당

let imagePath;
let path = getImagePath();
if(path !== null && path !== undefined && path !== '') {
	imagePath = path;
} else {
	imagePath = 'default.jpg''
}

let imagePath = getImagePath() || 'default.jpg';

AND(&&) 단락 평가

React.js에서 더욱 유용하게 사용 가능하다

if(isLoggedin) {
	goToHomepage();
}

isLoggedin && goToHomepage();

두 변수 교환

let x = 'hello', y = 55;

[x, y] = [y, x];

여러 조건 확인

indexOf() 또는 includes() method를 이용해보자

//Longhand 
if (value === 1 || value === 'one' || value === 2 || value === 'two') { 
     // Execute some code 
} 

// Shorthand 1
if ([1, 'one', 2, 'two'].indexOf(value) >= 0) { 
    // Execute some code 
}
// Shorthand 2
if ([1, 'one', 2, 'two'].includes(value)) { 
    // Execute some code 
}

Object 속성 할당

변수 이름과 object key 이름이 같다면 변수 이름만 적으면 된다

let firstname = 'Amitav';
let lastname = 'Mishra';

let obj = {firstname, lastname};

String to Int

//Longhand 
let total = parseInt('453'); 
let average = parseFloat('42.6'); 

//Shorthand 
let total = +'453'; 
let average = +'42.6';

문자열 반복

repeat() method를 사용해보자

//Longhand 
let str = ''; 
for(let i = 0; i < 5; i ++) { 
  str += 'Hello '; 
} 
console.log(str); // Hello Hello Hello Hello Hello 

// Shorthand 
'Hello '.repeat(5);
'sorry\n'.repeat(100);

지수 거듭 제곱

//Longhand 
const power = Math.pow(4, 3); // 64 

// Shorthand 
const power = 4**3; // 64

Double NOT 비트 연산자 (~~)

//Longhand 
const floor = Math.floor(6.8); // 6 //그래도 이거 추천

// Shorthand 
const floor = ~~6.8; // 6

array 최댓값 최솟값 찾기

// Shorthand 
const arr = [2, 8, 15, 4]; 
Math.max(...arr); // 15 
Math.min(...arr); // 2

For Loop

let arr = [10, 20, 30, 40]; 
//Longhand 
for (let i = 0; i < arr.length; i++) { 
  console.log(arr[i]); 
} 
//Shorthand 
//for of loop : 값 바로 접근
for (const val of arr) { 
  console.log(val); 
} 
//for in loop : index 접근
for (const index in arr) { 
  console.log(`index: ${index} and value: ${arr[index]}`); 
}

let obj = {x: 20, y: 50}; 
for (const key in obj) { 
  console.log(obj[key]); 
}

array 병합

let arr1 = [20, 30]; 
//Longhand 
let arr2 = arr1.concat([60, 80]); 
// [20, 30, 60, 80] 

//Shorthand 
let arr2 = [...arr1, 60, 80]; 
// [20, 30, 60, 80]

다단계 Object의 딥 클로닝

// 개체에 문자열과 숫자만 포함된 경우 사용
// function, undefined or NaN as value 포함된 경우 작동 안 됨
 const cloneObj = JSON.parse (JSON.stringify (obj));
// 단일 레벨 객체의 경우 짧게 
let obj = {x : 20, y : 'hello'}; 
const cloneObj = {... obj};

문자열에서 문자 가져오기

let str = 'jscurious.com'; 
// longhand
str.charAt (2); 
// shorthand
str [2];