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

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)


Edit: This answer is now incorrect; see "use strict"; per answer above (but JSLint is still handy).

This feature is akin to VB/VBA's Option Explicit and PHP7's declare(strict_types = 1);.


The feature you are looking for is sometimes called Option Explicit in other languages (I think it comes from Visual Basic). JavaScript does not have it. If you are looking for a way to check your variable usage, try JSLint.

Tags:

Javascript