Black lives matter
Portrait Dr. Axel Rauschmayer
Dr. Axel Rauschmayer
Homepage | Twitter
Cover of book “JavaScript for impatient programmers”
Book, exercises, quizzes
(free to read online)
Cover of book “Deep JavaScript”
Book (50% free online)
Cover of book “Tackling TypeScript”
Book (first part free online)
Logo of newsletter “ news”
Newsletter (free)

JavaScript quirk 4: unknown variable names create global variables

(Ad, please don’t block)

[This post is part of a series on JavaScript quirks.]

Normally, JavaScript automatically creates a global variable if you use an unknown variable name:

    > function f() { foo = 123 }
    > f()
    > foo
Thankfully, you get a warning in ECMAScript 5 strict mode [1]:
    > function f() { 'use strict'; foo = 123 }
    > f()
    ReferenceError: foo is not defined
  1. JavaScript’s strict mode: a summary