Javascript

[JavaScript] JavaScript/operator/typeof operator

OOQ 2022. 8. 1. 08:28
728x90
SMALL

#javascript

#javascript typeof operator

typeof Operator

typeof is an operator that returns the data type of a variable.

grammar

typeof variable

variable contains data or variables. Parentheses are allowed.

typeof(variable)

 

 

The returned values ​​are:

  • undefined: if the variable is not defined or has no value
  • number : if the data type is number
  • string : if the data type is a string
  • boolean : if the data type is boolean
  • object: if the data type is an object such as a function, array, etc.
  • function: if the value of the variable is a function
  • symbol : if the data type is symbol

for example

document.write( typeof 3 );

or

var a = 3;
document.write( typeof a );

will print number .

example

This is an example of outputting the data type while changing the value of the variable.

<!doctype html>
<html lang="en">
  <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>
728x90
LIST