TIL 15 | JavaScript Data types

song hyun·2021년 8월 9일
0

JavaScript

목록 보기
9/19
post-thumbnail

테이터 타입(Data Types)

최신 ECMAScript 표준은 7가지 데이터 유형을 정의한다.

  • Boolean
  • null
  • undefined
  • Number
  • String
  • Symbol (ES6+)
  • Object

null VS undefined

undefined는 데이터 타입, 값을 나타낸다. 즉, 변수만 선언했지만 할당하지 않은 변수를 말한다.

null의 타입 변수의 경우에는 명시적으로 값을 비어 있음을 나타내는데 사용한다. 즉, 아무것도 참조하지 있지 않다는 의미로 주로 객체를 담을 변수를 초기화 할 때 많이 사용한다.

// null
let nothing = null;
console.log(`value : ${nothing}, type : ${typeof nothing}`);

// undefined
let x;
console.log(`value : ${x}, type : ${typeof x}`);

자료형 변환(Data type conversion)

JavaScript는 동적 형지정(정형) 언어이다. 이는 변수를 선언할 때 데이터 형을 지정할 필요가 없음을 의미한다. 또한 데이터 형이 스크립트 실행 도중 필요에 의해 자동으로 변환됨을 뜻한다.

// 숫자 값이 문자로 변경되는 경우.
let x = 42;
x = 'The answer is ' + String(42); // "The answer is 42"

// 숫자형 문자 값이 숫자로 변경되는 경우.
let y = '12345';
y = Number(y) - 3; // 12342

// 문자 값을 숫자로 변경해야 하는 경우.
let img_width = '100px';
img_width = window.parseInt(img_width, 10); // 100

let img_height = '201.89px';
img_height = window.parseFloat(img_height, 10); // 201.89

리터럴(Literals)

JavaScript에서 값을 나타내기 위해 리터럴(literal)을 사용한다. 이는 말 그대로 스크립트에 부여한 고정값으로 변수가 아니다.

  • Array literals
  • Boolean literals
  • Floating-point literals
  • Numeric literals
  • Object literals
  • RegExp literals
  • String literals

단축 평가(short circuit evaluation)

논리 평가를 결정한 피연산자의 평가 결과를 그대로 반환한다. 이를 단축 평가 부르고 단축 평가는 아래의 규칙을 따른다.

  • true || anything : true
  • false || anything :anything
  • true && anything :true
  • false && anything : false
// 논리합 연산자(||)
console.log('x' || 'y'); // x
console.log(false || 'y'); // y
console.log('x' || false); // x

// 논리곱 연산자(&&)
console.log('x' && 'y'); // y
console.log(false && 'y'); // false
console.log('x' || false); // false

단축 평가는 객체가 null인 경우에 객체의 프로퍼티를 참조하면 TypeError가 발생한다. 이 경우 단축 평가를 사용하면 에러를 발생시키지 않는다.

const elem = null;
console.log(elem.value); // TypeError : Cannot red property 'value' of null
console.log(elem && elem.value); // null

또한 함수를 호출하지 않을 때 인수를 전달하지 않으면 매개변수는 undefined를 갖는다. 이 경우 기본값을 설정하면 undefined로 발생하는 에러를 방지할 수 있다.

function getStringLength(str) {
  str = str || '';
  return str.length;
}

getStringLength();     // 0
getStringLength('hello'); // 5
profile
Front-end Developer 🌱

0개의 댓글