[JavaScript / 연산자] typeof 연산자

typeof 연산자

변수의 데이터 타입을 반환하는 연산자입니다.

 

문법

typeof variable

  variable에는 데이터 또는 변수가 들어갑니다. 괄호를 사용해도 됩니다.

반환되는 값은 다음과 같습니다.

  • undefined : 변수가 정의되지 않거나 값이 없을 때
  • number : 데이터 타입이 수일 때
  • string : 데이터 타입이 문자열일 때
  • boolean : 데이터 타입이 불리언일 때
  • object : 데이터 타입이 함수, 배열 등 객체일 때
  • function : 변수의 값이 함수일 때
  • symbol : 데이터 타입이 심볼일 때

ex) document.write( typeof 3 ); //number

 

예제

<!doctype html>
<html lang="ko">
  <head>
    <meta charset="utf-8">
    <title>JavaScript</title>
    <style>
      body {
        font-family: Consolas, monospace;
        font-size: 20px;
        line-height: 1.6;
      }
    </style>
  </head>
  <body>
    <script>
      var a;
      document.write( "typeof a : " + typeof a + "<br>" );
      var a = 3;
      document.write( "typeof a = 3: " + typeof a + "<br>" );
      var a = 'Lorem';
      document.write( "typeof a = 'Lorem' : " + typeof a + "<br>" );
      var a = true;
      document.write( "typeof a = true : " + typeof a + "<br>" );
      var a = [ 'Lorem', 'Ipsum', 'Dolor' ];
      document.write( "typeof a = [ 'Lorem', 'Ipsum', 'Dolor' ] : " + typeof a + "<br>" );
      function a(){};
      document.write( "typeof a(){} : " + typeof a + "<br>" );
      var a = function(){};
      document.write( "typeof a = function(){} : " + typeof a + "<br>" );
      var a = Symbol();
      document.write( "typeof a = Symbol() : " + typeof a + "<br>" );
    </script>
  </body>
</html>

 

출처 : www.codingfactory.net/10288