[Vanilla JS] 변수와 데이터 타입

P1ush·2021년 5월 31일
0

TIL Vanilla JS

목록 보기
4/6
post-thumbnail

공부 날짜 : 2021-05-31

참고 자료


변수와 데이터 타입


let

변수 값을 재할당 할 수 있습니다. 단, 변수를 중복 선언은 할 수 없습니다.

let testValue;
testValue = 1;
console.log(testValue);
testValue = 2;
console.log(testValue);

//결과 : 1 2

cosnt

한번 상수로 선언된 변수에는 새로운 값을 넣을 수 없습니다.

const testValue = 1;
console.log(testValue);
testValue = 2; //오류 발생

type of : 변수가 무슨 타입인지 출력합니다.

let testValue1 = 1;
console.log(typeof testValue1);

//결과 : number 1

Boolean

true와 false 두 값을 가질 수 있습니다.

let testBoolean1 = Boolean('123');
console.log(testBoolean1); //결과 : true
let testBoolean2 = Boolean('');
console.log(testBoolean2); //결과 : false

undefiend

변수 안에 값이 들어갈 공간은 있지만, 값이 할당되지 않은 상태입니다.

let testValue;
console.log(typeof testValue, testValue);

//결과 : undefiend undefiend

null

변수에 값 (객체가)이 아예 없는 상태입니다.

let testValue3 = null;
console.log(testValue3);

//결과 : null

명시적으로 부재를 나타내고 싶다면 null을 사용하는게 더 좋다고합니다.
단, 객체를 사용할 때 어떤 속성의 부재를 null을 통해서 나타내는 쪽보다는 그 속성을 정의하지 않는 방식이 간편하므로 더 널리 사용된다고 합니다.

{
    name: 'Seungha',
    address: null
  }
  
- 아예 정의하지 않는 쪽이 더 좋음.
  {
    name: 'Seungha'
  }

symbol

  • ES6에서 추가된 타입입니다.
  • Symbol은 unique한 값을 만듭니다. (값이 중복되지 않습니다.)
let testSymbol1 = Symbol(1);
let testSymbol2 = Symbol(1);
console.log(typeof testSymbol1, testSymbol1);
console.log(typeof testSymbol2, testSymbol2);

console.log(testSymbol1 == testSymbol2);
console.log(testSymbol1 === testSymbol2);

/*
결과
symbol Symbol(1)
symbol Symbol(1)
*/

== (동등 연산자)

변수의 값을 서로 비교하는 연산자입니다.

a = 10, b = 5라고 할 때, console.log(a == b); 비교를 해보면 10은 5하고 같지 않기 때문에 false가 출력됩니다.


=== (일치 연산자)

왼쪽과 오른쪽의 변수 값과 데이터 타입이 정확하게 비교하는 연산자입니다.

== 연산자는 값만 서로 같으면 true를 출력합니다.

console.log(5 == 5) 

//true

하지만, === 연산자는 값과 데이터 타입까지 모두 같아야 true를 출력합니다.

console.log(5 === '5');

=== VS ==

둘중에 어떤 것을 써야될까요? 물론 쓰는건 개발자 마음이겠지만, 가급적이면 === (일치 연산자)를 쓰는게 더욱 정확하게 비교를 해서 좋다고 합니다.


==의 경우, 서로 같은 코드인데도 결과가 제각각입니다.

console.log("" == '0'); //false
console.log(0 == ""); //true
console.log(0 == '0'); //true
console.log(false == 'false'); //false
console.log(false == '0'); //true
console.log(false == undefined); //false
console.log(false == null); //false
console.log(null == undefined); //true
console.log('\t\r\n' == 0); //true

===를 사용하면 결과가 전부 동일합니다.

//전부 false
console.log("" === '0'); 
console.log(0 === ""); 
console.log(0 === '0'); 
console.log(false === 'false');
console.log(false === '0'); 
console.log(false === undefined); 
console.log(false === null);
console.log(null === undefined); 
console.log('\t\r\n' === 0);

0개의 댓글