内置类型(7)
- 空值-null
- 未定义-undefined
- 布尔值-boolean
- 数字-number
- 字符串-string
- 符号-symbol-es6新增
- 对象-object
除对象外,其他统称为基本类型
关于typeof
一般情况下,typeof的值都是内置类型
typeof undefined === "undefined"; // true
typeof true === "boolean"; // true
typeof 42 === "number"; // true
typeof "42" === "string"; // true
typeof {life: 42} === "object"; // true
typeof Symbol() === "symbol"; // true
特殊的看一下
关于null
typeof null === "object"; // true
所以当我们使用的时候,用复合条件来检测null值
var a = null;
(!a && typeof a === "object"); // true
关于function/数组
// 这么一看,function也是内置类型?
typeof function a() {} === "function"
function只是object的子类型。
1、变量是没有类型的,只有值才有。也就是说,语言引擎不要求变量总是持有与其初始化同类型的值。
2、对变量进行typeof操作时,得到的结果不是该变量的类型,而是该变量持有值的类型
关于undefined和undeclared(未声明)
在js中,undefined和undeclared是两回事
undefined:已经在作用域中声明,但是未赋值
undeclared:未在作用域中声明
所以控制台报错b is not defined等价于的是undeclared,并不是undefined,它容易让人误解成b is undefined
但是让人抓狂的是!!!
var a;
typeof a; // "undefined"
typeof b; // "undefined"

typeof b没有报错,因为typeof有一个特殊的防范机制。typeof的安全防范机制能帮我们做什么?
// 如何在程序中检查全局变量"DEBUG"才不会出现ReferenceError错误
// 这样会报错
if(DEBUG){
console.log('======>debug is starting')
}
// 这样是安全的
if(typeof DEBUG !== "undefined"){
console.log('======>debug is starting')
}
当然,通过window的安全防范方法也行,检查所有的全局变量是否是全局对象(window)的属性,注意,当代码需要运行在多种js环境中时,此时的全局对象并非总是window
