Javascript variables

From wikinotes
Revision as of 12:09, 5 February 2023 by Will (talk | contribs)
(diff) ← Older revision | Latest revision (diff) | Newer revision → (diff)

Variable Scope

execute-context-scoped:  # variable scoped to function, or module if not defined in function
block-scoped:            # variable scoped to the { ... } contents

Declaration & Assignment

var foo          // declare var (execute-context-scoped)
let foo          // declare var (block-scoped)
const foo        // declare constant (read-only) (block scoped)

var foo = "bar"  // declare/assign variable (execute context scoped)
let foo = "bar"  // declare/assign variable (block scoped)
var foo = (foo === undefined) ? "default" : foo  // assign if undefined

Introspection

var item = new Item()
item.constructor                   // get class from instance

// list methods, indexes, etc
Object.getOwnPropertyNames("foo")  // [ '0', '1', '2', 'length' ]

// list non-inherited methods
Reflect.ownKeys(Promise)           // ['length', 'name', 'prototype', 'all', 'resolve', ... ]
Reflect.has(Promise, "length")     // true