Data types in JavaScript

JavaScript is a dynamically typed language, so called dynamic because there are many implicit forced type conversions in the running of JavaScript code. For statically typed languages, a variable’s type is determined at declaration, and subsequent assignments can only be of a qualified type.

Conclusion: Variables in JavaScript are untyped, but values are typed. You can also say that data in JavaScript is “typed”.

Basic data types in JavaScript:

  • null
  • undefined
  • boolean
  • number
  • string
  • object
  • symbol

Arrays and functions are special objects. Functions are executable objects. The following code illustrates this:

const fn = function (target, name) {};
const arr = [1.2];

Object.getOwnPropertyNames(fn); // ["length", "name", "arguments", "caller", "prototype"]
Object.getOwnPropertyNames(arr); // ["0", "1", "length"]
Copy the code

You can see that the function is an object with a special property caller; The array attributes are numeric and contain the length attribute.

const num = 123;
const str = '456';
const bool = true;
const obj = { name: 'zz' };
const sym = Symbol('des');
const fn = function () {};
const fn1 = () = > {};
const arr = [];

console.log(typeof undefined); // undefined
console.log(typeof null); // object
console.log(typeof num); // number
console.log(typeof str); // string
console.log(typeof bool); // boolean
console.log(typeof obj); // object
console.log(typeof sym); // symbol
console.log(typeof fn); // function
console.log(typeof fn1); // function
console.log(typeof arr); // object

// It is recommended to use the following method to determine the data type
console.log(Object.prototype.toString.call(undefined)); // [object Undefined]
console.log(Object.prototype.toString.call(null)); // [object Null]
console.log(Object.prototype.toString.call(num)); // [object Number]
console.log(Object.prototype.toString.call(str)); // [object String]
console.log(Object.prototype.toString.call(bool)); // [object Boolean]
console.log(Object.prototype.toString.call(obj)); // [object Object]
console.log(Object.prototype.toString.call(sym)); // [object Symbol]
console.log(Object.prototype.toString.call(fn)); // [object Function]
console.log(Object.prototype.toString.call(fn1)); // [object Function]
console.log(Object.prototype.toString.call(arr)); // [object Array]
Copy the code

Typeof null returns object. This has been a problem for a long time and will not be fixed. The same is true of arrays.

Whether a data type is null therefore it is recommended to use the work Object. The prototype. ToString for judgment.

Although said array and function are special type of Object, but the Object. The prototype. ToString returns we expect results.