“var variable” returns undefined?

前端 未结 5 811
忘掉有多难
忘掉有多难 2020-12-11 03:44

When I run \"var variable = true;\" in chrome console I get \"undefined\" returned:

> var variable = true;
undefined

But when I run with

5条回答
  •  渐次进展
    2020-12-11 03:58

    I'd like to point out, that the answer provided by kennytm should be the accepted answer, at least for pedagogical purposes. The accepted answer doesn't answer why this is the case or provide deeper understanding.

    Like the null value in JavaScript, undefined indicates absence of value, but in a much deeper way. The following should be taken as complimentary to the above-mentioned answers:

    undefined is the value of variables that haven't been initialized and the value you get when you query the value of an object property or array element that doesn't exist. This value is also returned by functions that have no return value, and the value of function parameters for which no argument is supplied. undefined is a predefined global variable (not a language keyword like null) that is initialized to the undefined value.

    You might consider undefined to represent a system-level, unexpected, or error-like absence of value and null to represent program-level, normal, or expected absence of value.

    -- Flanagan, David. JavaScript: The Definitive Guide: Activate Your Web Pages (Definitive Guides) . O'Reilly Media. Kindle Edition.

    Also, makes sure to check out both the accepted and the second most voted answer for further reference: Chrome/Firefox console.log always appends a line saying undefined

提交回复
热议问题