33

Reference Error: JavaScript

 5 years ago
source link: https://www.tuicool.com/articles/hit/baIfU3Q
Go to the source link to view the article. You can view the picture content, updated content and better typesetting reading experience. If the link is broken, please click the button below to view the snapshot at that time.

How would you feel if, when you went to a job interview, you found out that the company for which you were hoping to interview didn't even exist?

Obviously, you'd get angry.

Exactly the same thing happens with JavaScript, too.

When any value is assigned to an undeclared variable, an assignment without the ar keyword, or a variable that is not in your current scope, it might lead to unexpected results. That’s why JavaScript presents a ReferenceError: assignment to undeclared variable "x" in strict mode. And this error causes a problem in the execution of functions.

If you’ve begun to try out JavaScript you might have encountered some pretty baffling errors. I know I sure did…

ReferenceError: Assignment to Undeclared Variable “x”

Errors about undeclared variable assignments occur in strict mode code only. In non-strict code, they are silently ignored.

Code without ‘var’ keyword

function foo() { 
  'use strict'; 
  bar = true; //variable not declared
} 
foo();

What you get after executing the above program? An error?

jUjemiQ.png!web

How You Need to Code

Insert var in front of your variable and see your program running:

function foo() {
  'use strict';
  var bar = true; //declared variable here
}
foo();

Likewise, there are many scripting factors possible to generate reference errors in JavaScript.

ReferenceError: "x" is not defined
ReferenceError: deprecated caller or arguments usage
ReferenceError: can't access lexical declaration`X' before initialization
ReferenceError: reference to undefined property "x"
ReferenceError: invalid assignment left-hand side

About Joyk


Aggregate valuable and interesting links.
Joyk means Joy of geeK