본문 바로가기

개발/javascript

[javascript] 응용1

Trusy and Falsy

참같은 값, 거짓같은 값

let a= "";

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

-->False

let a= "string";

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

-->True

 

이러한 것들은javascipt의 자신만의 기준으로 True와 False를 나누는 Trusy와 Falsy에 의한 속성에 의한 결과이다. 

 

{ }, 123, "0", Infinity => True  :Trusy

null, undefined, 0, -0, NaN,""=>False: Falsy

 

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

let person;
const name =getName(person);
console.log(name);

이렇게 person이라는 값이 undefined가 되면 error가 발생하는데 객체가 포함되어 있지 않아서 
점표기법을 사용할 수  없기 때문이다. 


const getName =(person) => {
  if (person===undefined||person ===null){
    return "객체x"
  }
  return person.name;
};

let person;
const name =getName(person);
console.log(name);

이런식으로 조건식을 사용하여 해결할 수 있다.
const getName =(person) => {
  if (!person){//false Not=>True
    return "객체x"
  }
  return person.name;
};

let person=null;
const name =getName(person);
console.log(name);

함수가 복잡해지고 많아질 수록 조건문을 사용하면 복잡해지기 때문에 Falsy속성을 활용해서 

해결 할 수 있었다. 

 

삼항연산자

(조건문 ? 참일때: 거짓일 때)

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

"a>0보다 크면 양수 아니면 음수"

let a =[];
a.length===0?console.log("빈배열"):console.log("안 빈 배열");

let a =[];
const arrayStatus= a.length===0?"빈배열":"안 빈 배열";
console.log(arrayStatus);

trusy falsy를 활용한 삼항연산자

let a=[];
const result =a? true: false;
console.log(result);

중첩을 활용한 삼항연산자

let score=60;

score>=90
?console.log("A+")
:score>=50
?console.log("B+")
:console.log("F")

단란회로평가

:논리연산자 활용한 문법

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

let person;
const name=getName(person);
console.log(name);

 

 

'개발 > javascript' 카테고리의 다른 글

[javascript]동기&비동기  (0) 2023.07.24
[javascript]응용  (0) 2023.07.23
[javascript]기본정리5  (0) 2023.07.03
[javascript]기본정리4  (0) 2023.07.02
[javascript]기본정리3  (0) 2023.07.02