DEV Community

Mark Kozel
Mark Kozel

Posted on

2 1

Mutability of JavaScript

I love the way JavaScript code has a dynamic aspect that allows for on-the-fly changes

Coming from a Safety-Critical Software background, any dynamic construct, like inheritance, was discourages

Now, learning web programming I am loving the freedom JavaScript includes. Some are likely an effect of being interpreted, but others are just plain cool

Object Bracket Notation

ability to reference object elements as an array, somewhat like PHP's associative arrays

let myObj = {'prop1': 14};
myObj['prop1'] = 41;
Enter fullscreen mode Exit fullscreen mode

Adding Object Elements on-the-fly

Coming from C/C++ OOD/P, everything is fixed and unbending

With JS Object, you can tack on a new element, including functions

I had some fun with this in an NPM module Quick JSON Config I wrote a while back

As the node app reads in each top-level element of the JSON file, it adds get/set function to it's class instance

  /**
   * Embeds each json element into this class. Creates a simple get/set method for each
   * @param {object} el - json key-value pair for embedding
   */
  _embedElement(el) {
    let getName = `get${el}`;
    this[getName] = function () {
      return this._jsonData[el];
    }

    let setName = `set${el}`;
    this[setName] = function (newVal) {
      if (typeof newVal === typeof this._jsonData[el]) {
        this._jsonData[el] = newVal;
      }
    }
  }
Enter fullscreen mode Exit fullscreen mode

Here I create the functions to get/set the element, then tack it on to the instance using the Bracket Notation

Promisify Functions

Working in Node and using some older (well, actually, it is more like not maintained packages), the mutations are used to wrap function is async/await and Promise constructs

I have not looked into how packages like bluebird does this, but I expect it is similar to the above items I expressed

Of Course...

This means developers must understand these constructs so they do not shoot themselves (or their customers) in the foot

While safety-critical software has rules and limitations, many are to prevent letting the runtime environment make decisions and change how your code executes

SurveyJS custom survey software

Simplify data collection in your JS app with a fully integrated form management platform. Includes support for custom question types, skip logic, integrated CCS editor, PDF export, real-time analytics & more. Integrates with any backend system, giving you full control over your data and no user limits.

Learn more

Top comments (0)

A Workflow Copilot. Tailored to You.

Pieces.app image

Our desktop app, with its intelligent copilot, streamlines coding by generating snippets, extracting code from screenshots, and accelerating problem-solving.

Read the docs