본문 바로가기
Front-End/JAVASCRIPT

[ JavaScript ] 자바스크립트 응용 ①

by 2CHAE._.EUN 2022. 8. 27.

[ Truthy & Falsy ]

 

let a = "chaechae";

if( a ){
    console.log("True")
}else{
    console.log("False");
}

//True

 

자바스크립트의 조건식에는 Boolean 타입을 적어주지 않아도 참과 거짓을 구분할 수 있는 성질이 있다.

 

Truthy : 배열, 객체, 숫자 값, 문자열, Infinity

* 빈 배열, 빈 객체도 포함

 

Falsy : null, undefined, 0, Nan, ""( 빈 문자열 )

 

함수의 파라미터로 전달받은 인자가 객체인지 혹은 undefined / null이 아닌지 판단해야할 경우 Truthy와 Falsy를
이용할 수 있다.

 

const getName = (person) =>{
    if( person === undefined || person === null ){
        return "에러"
    }
    return person.name;
}

let person1 = {
    name : "2chaechae"
};

let person2;

let person3 = null;

const name1 = getName(person1); 
const name2 = getName(person2);
const name3 = getName(person3);

console.log(name1); //2chaechae
console.log(name2); //에러
console.log(name3); //에러

 

Falsy 속성 하나로 undefined와 null을 구별하는 방법 : not 연산자를 활용

 

const getName = (person) =>{
    if( !person ){ // false NOT => True
        return "에러"
    }
    return person.name;
}

let person1 = {
    name : "2chaechae"
};

let person2;

let person3 = null;

const name1 = getName(person1); 
const name2 = getName(person2);
const name3 = getName(person3);

console.log(name1); //2chaechae
console.log(name2); //에러
console.log(name3); //에러

 


[ 삼항 연산자 ]

 

let a = 3;

if( a >= 0 ){
    console.log("양수");
}
else{
    console.log("음수");
}

a >= 0? console.log("양수") : console.log("음수");

 

삼항 연산자는 조건문을 줄여줄 수 있는 연산 식이다.

 

조건식 ? 참일 때 수행할 식 : 거짓일 때 수행할 식;

 

let a = [];

if( a.length === 0 ){
    console.log("배열에 데이터가 없습니다.");
}
else{
    console.log("배열에 데이터가 있습니다.");
}

a.length === 0 ? console.log("빈 배열") : console.log("데이터가 존재");

 

삼항 연산자로 값을 명시하게 되면 대입 연산자를 이용해 값을 받아볼 수 있다. 

 

let a = [];

const arrayStatus = a.length === 0 ? "빈 배열" : "데이터가 존재";
console.log(arrayStatus);

 

삼항 연산자도 Truthy와 Falsy를 이용할 수 있다.

 

let a;

const result = a ? true : false;

console.log(result); //false

 

삼항 연산자를 중첩해서 사용할 수 있다.  ( 가독성이 떨어지는 경우 if 조건문을 활용하는 것이 좋음 )

 

let score = 85;

const result = score >= 90 ? "A" : score >= 80 ? "B" : "F";

console.log(result); // B

 


[ 단락회로 평가 ]

 

단락회로 평가 : 왼쪽에서 오른쪽으로 연산하게 되는 논리 연산자의 연산 순서를 이용하는 문법

 

피연산자 중에 뒤에 있는 피연산자를 확인할 필요 없이 바로 연산을 끝내는 것이 단락회로 평가이다.

&&의 첫번째 피연산자가 false일 경우는 뒤를 확인할 필요 없이 바로 Falsy한 값을 리턴하게 된다.

||의 첫번째 피연산자가 true일 경우도 뒤를 확인할 필요 없이 바로 Truty한 값을 리턴하게 된다. 반대로 첫번째 피연산자가 false일 경우 뒤에 있는 두번째 피연산자를 확인하게 되고 그 값을 리턴한다.

 

&&나 ||의 두 피연산자가 모두 True일 경우는 뒤에 있는 두번째 피연산자의 값을 리턴하게 된다.

 

console.log( false && true ); //false

console.log( true || false ); //true

 

* 논리 연산자 : &&, ||, !

 

논리 연산자의 피연산자로 Truty와 Falsy를 사용하게 될 경우 

 

const getName = (person)=>{
    if(!person){
        return "에러";
    }
    return person.name;
}

let person;

const name = getName(person);
console.log(name); //에러

 

const getName = (person)=>{
    return person && person.name;
}

let person;

const name = getName(person);
console.log(name); //undefined

 

&&의 양쪽의 피연산자로 Truthy와 Falsy한 값을 주었을 때, person 파라미터가 undefined한 값을 받게 된다면 && 연산에서 첫번째 피연산자가 Falsy한 값을 갖게 되므로 뒤에 있는 두번째 피연산자를 고려할 필요가 없어진다. person.name 값을 고려할 필요가 없기 때문에 person 자체이고 Falsy한 값인 undefined을 그대로 리턴하게 된다.

 

const getName = (person)=>{
    const name = person && person.name;
    return name || "이름이 존재하지 않습니다.";
}

let person1;

const name1 = getName(person1);
console.log(name1); //이름이 존재하지 않습니다.

let person2 = {
    name : "2chaechae"
};

const name2 = getName(person2);
console.log(name2); //2chaechae

 

||의 첫번째 피연산자가 Truthy할 경우에는 뒤에 있는 두번째 피연산자를 고려할 필요없이 바로 Truthy한 값을 리턴하게 된다. ||의 단락회로 평가는 첫번째 피연산자가 true이거나 Truthy일 경우 바로 그 값을 반환하고 종료하기 때문이다. 반대로 첫번째 피연산자가 Falsy일 경우 뒤에 있는 두번째 피연산자를 확인하고 그 값을 리턴하게 된다.

 


[ 조건문 업그레이드 ]

 

1. includes()를 사용해서 여러 케이스 중 하나인지 확인하는 조건문

 

function ramen(food){
    if( food === "신라면" || food === "너구리" || food === "왕뚜껑"){
        return true;
    }
    return false;
}

const food = ramen("너구리");
console.log(food); // true

 

조건문의 조건이 매우 많을 경우 대부분 다 문자열이기 때문에 문자열로 이루어진 라면들 중에 입력 받은 값이 있는지
includes 함수를 사용해서 확인하면 된다. 

 

* includes : 전달받은 파라미터가 배열안에 존재하는지 확인해주는 함수

 

function ramen(food){
    if( ["신라면", "너구리", "왕뚜껑"].includes(food) ){
        return true;
    }
    return false;
}

const food = ramen("너구리");
console.log(food); // true

 

2. 주어진 값에 따라 각각 다른 값을 반환하는 조건문

 

const gameType = (type) => {
    if( type === "RPG"){
        return "메이플스토리";
    }   
    if( type === "FPS"){
        return "배틀그라운드";
    }  
    if( type === "Multi"){
        return "폴가이즈";
    }    
    return "알 수 없음";
}

console.log(gameType("RPG")); // 메이플스토리

 

조건문의 존재가 매우 많을 경우 객체의 프로퍼티에 접근하는 괄호 표기법을 통해 해결할 수 있다.

 

const game = {
    RPG : ["메이플스토리", "로스트아크"],
    FPS : ["배틀그라운드", "발로란트", "오버워치", "에이펙스"],
    MULTI : ["폴가이즈", "슈퍼마리오브라더스"],
    FIGHTING : ["나루티밋스톰", "히노카미혈풍담"],
    MOBA : "리그오브레전드"
};

const gameType = (type) => {
    return game[type] || "알 수 없음";
}

console.log(gameType("FPS")); // [ '배틀그라운드', '발로란트', '오버워치', '에이펙스' ]

 


[ 비 구조화 할당 ]

 

비 구조화 할당 / 구조 분해 할당 : 배열이나 객체에서 원하는 값을 빠르고 쉽게 접근할 수 있는 방법

 

1. 배열의 비 구조화 할당 :  []를 활용해서 배열의 값을 순서대로 변수에 할당해서 사용할 수 있는 방법

 

배열안에 변수를 선언하고 오른쪽에 배열을 할당해주면 index에 맞게 각각 할당이 된다. 

 

let arr = ["one", "two", "three"];

let one = arr[0];
let two = arr[1];
let three = arr[2];

let [one1, two1, three1] = arr;

console.log(one, two, three); // one two three
console.log(one1, two1, three1); // one two three

 

let [one, two, three] = ["one", "two", "three"]; // 배열의 선언 분리 비 구조화 할당

console.log(one, two, three); // one two three

 

값을 할당받지 못하는 변수는 undefined을 갖게 된다. 변수에 undefined가 할당되는 경우를 방지하기 위해 기본 값을 설정할 수 있다. 

 

let [one, two, three, four="four"] = ["one", "two", "three"];

console.log(one, two, three, four); // one two three four

 

* swap

 

let a = 10;

let b = 20;

let tmp = 0;

console.log(a,b); // 10 20

tmp = a;
a = b;
b = tmp;

console.log(a,b); // 20 10

 

let a = 10;

let b = 20;

let tmp = 0;

console.log(a,b); // 10 20

[ a,b ] = [ b,a ];

console.log(a,b)  // 20 10

 


2. 객체의 비 구조화 할당 : 객체의 key 값을 기준으로 객체의 value를 변수에 할당해 사용할 수 있는 방법

* 변수의 이름과 key값의 이름이 반드시 같아야 한다. 대신 순서가 상관이 없음.

 

let object = {
    one : "one",
    two : "two",
    three : "three"
};

let one = object.one;
let two = object.two;
let three = object.three;

console.log(one, two, three); // one two three

 

let object = {
    one : "one",
    two : "two",
    three : "three"
};

let {one, two, three} = object;

console.log(one, two, three); // one two three

 

변수의 이름이 key 값이 아니라 다르게 사용하고 싶은 경우에는 할당시에 : 를 이용해주면 된다. 

 

let object = {
    one : "one",
    two : "two",
    three : "three"
};

let { one:newOne , two, three} = object;

console.log( newOne, two, three ); // one two three

 

배열 비 구조화 할당과 마찬가지로 객체에 존재하지 않은 프로퍼티를 할당할 경우 undefined가 할당이 된다. 
마찬가지로 기본 값을 설정해줄 수 있다. 

 

let object = {
    one : "one",
    two : "two",
    three : "three"
};

let { one:newOne , two, three, four="four", five} = object;

console.log( newOne, two, three, four, five ); // one two three four undefined

 


[ spread 연산자 ]

 

여러 개의 객체에서 중복된 값의 프로퍼티를 계속해서 작성해야하는 경우 spread 연산자를 이용할 수 있다.

 

const cookie = {
    base : "cookie",
    madeIn : "korea"
};

const chocoCookie = {
    base : "cookie",
    madeIn : "korea",
    topping : "choco"
};

const butterCookie = {
    base : "cookie",
    madeIn : "korea",
    topping : "butter"
};

const blueberryCookie = {
    base : "cookie",
    madeIn : "korea",
    topping : "blueberry"
};

 

...으로 표현하는 것을 spread 연산자라고 한다. spread 연산자는 객체의 값을 새로운 객체에 펼쳐주는 역할을 한다. 

 

const cookie = {
    base : "cookie",
    madeIn : "korea"
};

const chocoCookie = {
    ...cookie,
    topping : "choco"
};

const butterCookie = {
    ...cookie,
    topping : "butter"
};

const blueberryCookie = {
    ...cookie,
    topping : "blueberry"
};

console.log(butterCookie); // { base: 'cookie', madeIn: 'korea', topping: 'butter' }

 

spread 연산자는 객체의 프로퍼티를 펼치는 것 뿐만 아니라 배열에도 사용할 수 있다. 

 

spread 연산자를 이용해서 배열의 원소를 순서대로 펼쳐서 합치는 것이 가능하다. 또한 중간에 다른 값을 삽입하더라도 유연하게 작동한다.

 

const hunter = [ "남헌터", "여헌터" ];
const hunterJob = ["스카우터", "데빌헌터", "호크아이", "건슬링어", "블래스터"];

const allHunter = [ ...hunter, ...hunterJob ];
console.log(allHunter); // [ '남헌터', '여헌터', '스카우터', '데빌헌터', '호크아이', '건슬링어', '블래스터' ]

const allHunter = [ "로스트아크" , ...hunter , ...hunterJob ];
console.log(allHunter); // [ '로스트아크', '남헌터', '여헌터', '스카우터', '데빌헌터', '호크아이', '건슬링어', '블래스터' ]