javascript.lang.best-practice.assigned-undefined.assigned-undefined

profile photo of semgrepsemgrep
Author
4,397
Download Count*

undefined is not a reserved keyword in Javascript, so this is "valid" Javascript but highly confusing and likely to result in bugs.

Run Locally

Run in CI

Defintion

rules:
  - id: assigned-undefined
    languages:
      - javascript
      - typescript
    message: '`undefined` is not a reserved keyword in Javascript, so this is
      "valid" Javascript but highly confusing and likely to result in bugs.'
    pattern-either:
      - pattern: undefined = $X;
      - pattern: var undefined = $X;
      - pattern: let undefined = $X;
      - pattern: const undefined = $X;
    severity: WARNING
    metadata:
      category: best-practice
      technology:
        - javascript
      license: Commons Clause License Condition v1.0[LGPL-2.1-only]

Examples

assigned-undefined.js

// 'undefined' is "assignable" syntactically but it's read-only (since
// ECMAScript 5), so its value will remain 'undefined'.
// https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/undefined

// ok:assigned-undefined
alert(undefined); //alerts "undefined"
// ruleid:assigned-undefined
var undefined = "new value";
alert(undefined) // alerts "new value"

// ruleid:assigned-undefined
undefined = "new value";
alert(undefined) // alerts "new value"