공부/javascript
[ javascript ] 알고있으면 유용한 JS문법
신입개발자
2021. 6. 27. 09:10
1. 삼항연산자
condition ? true : false // 조건 ? 결과가 true 일시 : 결과가 false 일시
2. Truthy and Falsy
// Falsy 한 값 : false와 비슷한 값
console.log(!undefined); // true
console.log(!null); // true
console.log(!0); // true
console.log(!''); // true
console.log(!NaN); // true
console.log(!false); // true
// Truthy 한 값 : true와 비슷한 값
console.log(!3); // false
console.log(!'hello'); // false
console.log(!['array']); // false
console.log(![]); // false
console.log(!{}); // false
let value = '';
// valse를 true인지 false인지 체크해서 변수에 넣는 조건문을 작성한다면
// if 문
let truthy = null;
if( value ){
truthy = true;
} else {
truthy = false;
}
// 삼항연산자
let truthy = value ? true : false;
// !표로 넣기
let truthy = !!value
3. 단축 평가 논리 계산법
[ AND 연산자 ]특정값이 유효 할때 어떤 값을 조회해야 할때 사용(React에서는 자주 쓴다고함)
const dog = {
name: '멍멍이',
};
function getName(animal){
if (animal) {
return animal.name; // animal에 name값이 있다면 name값을 리턴
}
return undefined; // animal에 name값이 없다면 undefined 를 리턴
}
const name = getName(dog);
console.log(name); // 멍멍이
const name2 = getName();
console.log(name); // undefined
이 코드를 단축할수 있습니다 단축한다면
const dog = {
name: '멍멍이',
};
function getName(animal){
return animal && animal.name;
// and 연산자로 animal의 값이 있고 name 값이 있다면 name값을 리턴
// 앞의 값이 true 이면 뒤에 값을 리턴
// 앞의 값이 false 라면 false 값을 리턴
};
const name = getName(dog);
console.log(name); // 멍멍이
const name2 = getName();
console.log(name); // undefined
다른 예시
console.log(true && 'hello'); // hello
console.log(false && 'hello'); // false
console.log('hello' && 'bye'); // bye
console.log(null && 'hello'); // null
console.log(undefined && 'hello'); // undefined
console.log('' && 'hello'); // ''
console.log(0 && 'hello'); // 0
console.log(1 && 'hello'); // hello
const object = null;
const name = object && object.name;
console.log(name); // null
[ OR 연산자 ] 어떤한값 이 없을때 "그거 대신에 이거 사용할래" 할때 사용하면 유용합니다
const namelessDog ={
name: '멍멍이',
};
function getName(animal){
const name = animal && animal.name;
if (!name) {
return '이름이 없는 동물 입니다';
}
return name;
}
const name = getName(namelessDog);
console.log(name); // 멍멍이
이 코드도 단축할 수 있습니다
const namelessDog ={
name: '멍멍이',
};
function getName(animal){
const name = animal && animal.name;
return name || '이름이 없는 동물 입니다';
}
const name = getName(namelessDog);
console.log(name); // 멍멍이
OR 연산자 다른 예시
// 앞이 Falsy한 값이라면 뒤에 있는 값을 리턴
console.log(false || 'hello'); // hello
console.log('' || 'hello'); // false
console.log(null || 'bye'); // bye
console.log(undefined || 'hello'); // null
console.log(0 || 'hello'); // 0
// 앞이 Truthy한 값이라면 앞에 값을 리턴 뒤의 값을 안봅니다
console.log(1 || 'hello'); // 1
constole.log(true || 'hi'); // h1
constole.log('text' || 'bye'); // text
console.log([] || 'bye'); // []
4. 함수의 기본 파라미터
// 함수를 호출하게 될때 원래 넣어야할 파라미터를 넣지 않게 되었을때
// 기본값으로 사용할 값을 지정하는 문법
function calculateCircleArea(r) {
return Math.PI * r * r
}
const area = calculateCircleArea();
console.log(area); // NaN
// 기본값 지정
function calculateCircleArea(r = 1) {
return Math.PI * r * r
}
5. 조건문 스마트하게 쓰기
// 특정 값이 여러 값중 하나인데 그 값을 찾아야할때
// 쓸대없이 조건문 코드가 많습니다
function isAnimal(text) {
return text === '고양이' || text === '개' || text === '거북이';
}
// 비교할 문자들을 배열안에 넣어 includes함수를 이용해 리턴하기
function isAnimal(text) {
const animals = ['개','고양이','거북이'];
return animals.includes(text); // true
}
// 화살표 함수로 한줄로 쓰기
const isAnimal = (text => ['개','고양이','거북이'].includes(text));
다른 예시
// 입력받은 값의 따라 다른 결과를 리턴해야 할때
// if문이 많아 지저분해보입니다
function getSound(animal){
if(animal === '개') return '멍멍';
if(animal === '고양이') return '야옹';
if(animal === '참새') return '짹짹';
if(animal === '비둘기') return '구구';
return '...?';
}
console.log(getSound('개')); // 멍멍
console.log(getSound('고양이')); // 야옹
console.log(getSound('비둘기')); // ...?
// switch문 사용하기
// 어떻게 보면 if문이 좀더 깔끔해 보입니다
function getSound(animal){
switch (animal) {
case '개':
return '멍멍';
case '고양이':
return'야옹';
case '참새':
return '짹짹';
case '비둘기';
return '구구';
default:
return '...?';
}
}
console.log(getSound('개')); // 멍멍
console.log(getSound('고양이')); // 야옹
console.log(getSound('비둘기')); // ...?
// 객체를 이용해서 스마트하게 작성하기
function getSound(animal){
const sound = {
개: '멍멍',
고양이:'야옹',
참새:'짹짹',
비둘기: '구구'
};
return sound[animal] || '...?';
// OR연산자를 써서 sound 객체안에 animal값이 없으면 ...? 리턴
}
console.log(getSound('개')); // 멍멍
console.log(getSound('고양이')); // 야옹
console.log(getSound('비둘기')); // ...?
6. 비구조화 할당( 구조 분해 )
// 객체 비구조화 할당
const object = { a: 1, b: 2};
// 객체 안에 있는 a 와 b를 꺼내는 방법
// 코드가 길지는 않지만 비효율 적
const a = object.a;
const b = object.b;
// 비구조화 문법 적용
const {a, b} = object;
console.log(a); // 1
console.log(b); // 2
const amimal ={
name: '멍멍이',
type: 'Dog'
}
// nickname 변수에 animal객에의 name값 넣기
const nickname = animal.name;
// 비구조화 문법 적용
const {name: nickname} = animal;
console.log(nickname); // 멍멍이
//배열 비구조화 할당
const array = [1];
const [one, two =2 ] = array; // two의 기본값을 설정
// 객체 안에 있는 배열의 값을 꺼내오는 방법
// 객체안에 있는 값들을 가져와 세로운 객체에 정리해서 넣어주기
const deepObject = {
state: {
information: {
name: 'velopert',
language: ['korean', 'english', 'chinese']
}
},
value:5
}
const {name, language, [first, second]} = deepObject.state.information;
const { value } = deepObject;
const extracted = {
name,
language,
value
}
console.log(extracted);
// 비구조화 할당 적용
const {
state: {
information: {
name, language: [firstLang, secondLang]
}
},
value
} = deepObject.state.information;
const extracted ={
name,
firstLang, secondLang,
value
}
console.log(extracted);
// 비구조화 문법을 써도 그다지 효율적으로 보이지는 않습니다