JavaScript 什么是未声明和未定义变量
未定义: 当一个变量被声明但没有被赋予任何值时发生。未定义不是一个关键字。
未声明: 当我们尝试访问任何未初始化或之前未声明的变量时发生,使用 var 或 const关键字。如果我们使用 ‘typeof’ 运算符来获取一个未声明变量的值,我们将会遇到 运行时错误 并且返回值为 “undefined” 。未声明变量的作用域始终为全局。
例如:
未定义:
let geek;
undefined
console.log(geek)
未声明:
// ReferenceError: myVariable is not defined
console.log(myVariable)
示例1: 这个示例说明了使用未声明变量的情况。
function GFG() {
// 'use strict' verifies that no undeclared
// variable is present in our code
'use strict';
x = "GeeksForGeeks";
}
GFG(); // Accessing the above function
输出:
ReferenceError: x is not defined
示例 2: 这个示例检查一个给定的变量是否未定义。
function checkVar() {
let string;
if (typeof variable === "undefined") {
string = "Variable is undefined";
} else {
string = "Variable is defined";
}
console.log(string);
}
checkVar();
输出
Variable is undefined