Variable Scope

You need to know three rules to understand scoping in CoffeeScript:

  1. Every function creates its own scope.

  2. Functions are the only constructs that create scope.

  3. Each variable lives in the outermost scope in which a value is (potentially) assigned to it.

The first two rules are an innate part of the JavaScript language. (More precisely, it’s how variables are scoped with the var keyword. A different scoping keyword, let, is also supported in the ECMAScript 6 draft spec and a handful of forward-looking JavaScript runtimes.) CoffeeScript follows suit, which means that conditionals and loops do not create scope.

The last rule allows CoffeeScript to do away with var. If you write myBologna = ’Oscar Mayer’, it’s understood that you ...

Get CoffeeScript, 2nd Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.