Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to force JavaScript to declare variables before use?

Tags:

javascript

Is it possible, perhaps by using some directive in the JavaScript code, to throw warnings or errors if variables are used without being declared first?

In case that isnt possible, is there perhaps some plugin to force Eclipse (or any other IDE) to detect undeclared variables?

like image 364
thunderboltz Avatar asked May 26 '11 04:05

thunderboltz


1 Answers

Yes, it's possible to do this using strict mode. You enable it by putting a statement containing the string literal "use strict" at the top of a file or function to enable strict mode for that scope.

"use strict";
doesNotExist = 42; // this throws a ReferenceError

This feature is now supported by all updated browsers. Older browsers wont' throw an error since "use strict"; is a valid statement and is simply ignored by browsers that don't support it. You can therefore use this to catch bugs while developing, but don't rely on it throwing an exception in your users' browsers.

Strict mode

JavaScript's strict mode is a way to opt in to a restricted variant of JavaScript, thereby implicitly opting-out of "sloppy mode". Strict mode isn't just a subset: it intentionally has different semantics from normal code.

Strict mode for an entire script is invoked by including the statement "use strict"; before any other statements.
(Source, Documentation)

like image 142
hammar Avatar answered Sep 23 '22 05:09

hammar