When does an undefined variable throw an Uncaught TypeError instead of just having a value of 'undefined'?

时间:2018-10-02 09:16:11

标签: javascript error-handling undefined undefined-behavior

Basically in the code I am editing, there's a function that receives an object argument that has 2 possible key/value pairs, but only either gets used depending on some condition:

This is the function that destructures the foobar into the individual keys:

function someFunction({ foo, bar }) {
  console.log(foo); // can be either { foo: "123"} or undefined
  console.log(bar); // can be either { bar: "321"} or undefined
}

This is where we pass the foobar argument to someFunction():

function anotherFunction(foobar) {
  console.log(foobar); // can be either { foo: "123"} or { bar: "321"}
  someFunction(foobar);
}

This is where the foobar argument originates and its value depends on some condition:

if(someConditionIsMet) {
  anotherFunction({ foo: "123"});
} else {
  anotherFunction({ bar: "321"});
}

But sometimes, if I have an undefined variable somewhere, I will get an Uncaught TypeError: Cannot read property of undefined and the program won't run at all.

E.g. when I call someFunction(foobar), I was expecting to get an Uncaught TypeError because definitely one of the variables will be undefined. However, here the function still runs.

Why is this so?

2 个答案:

答案 0 :(得分:1)

未定义变量的确切含义是:您在代码中使用的变量名称,但是运行时却不知道它应该引用什么,因为您从未引入过 该变量名。

在这里,您清楚地将foobar引入为功能参数。运行时很清楚这些变量来自何处,它们的作用域是什么,等等。只是它们没有被赋值/它们拥有值undefined未定义变量是您突然用到的变量,没有用varletconst或作为函数参数声明它们。例如:

console.log(foo);

我从未定义foo是什么,它来自哪里或它的值应该是什么,所以这是一个错误。

答案 1 :(得分:0)

许多编程语言都是基于以下原则设计的:如果一段代码不太可能按预期方式运行,则尽早s窃比简单地使代码以意外方式运行更为可取。尽管JavaScript的许多方面在这方面无济于事,但"use strict"方言会在某些情况下尝试提供帮助。

从这方面来说,此处描述的情况尤为重要,因为在非"use strict"方言中,尝试在未定义功能的函数中使用变量具有有效的指定含义(创建变量在外部环境中),有时是依赖的。尽管在某些情况下#include<stdio.h> #include<stdlib.h> char concatenation(); int main(int argc, char const *argv[]) { int c, ouinon, i; int n; char parentheses[n]; char l; printf("- - - - Parenthesage - - - -\n"); printf("Program élaboré pour faire la concatenation des parentheses.\n"); for(i = 0; i < n; i++){ printf("tapez ()[]: \n"); gets(parentheses); printf(" %c", parentheses[i]); l = parentheses[i]; if(ouinon == 0){ printf("Continue 0 arrete 1: \n"); n++; } } concatenation(l); } char concatenation(){ char a; // prendre la variable 'char l' avec les informations du tableaux printf(" %c", a); } 会使具有一种有效含义的代码具有不同的有效含义,但是大多数情况不会经常出现。如果尝试使用未在函数中定义的变量的代码的含义被更改为在该函数中创建变量,那么依赖旧行为的代码将停止工作,而无需任何诊断说明原因。

相关问题