DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’»

DEV Community πŸ‘©β€πŸ’»πŸ‘¨β€πŸ’» is a community of 966,155 amazing developers

We're a place where coders share, stay up-to-date and grow their careers.

Create account Log in
RocketMaker69
RocketMaker69

Posted on

Using Object.defineProperties()

Hello, today we will learn how to use Object.defineProperties(/* object */, {
// properties here...
})
, which has the following arguments:
object (1st arg): The object to define the properties to.

props: The properties to add add to the object.

Here's an example:

let object = { };

Object.defineProperties(object, {
  a: { value: 4 }
});

console.log(object.a);   // 4
Enter fullscreen mode Exit fullscreen mode

To begin, we pass object as the first argument, so we will add properties to object. Then, we pass an object (the same as a Python Dictionary) as the second argument. You see that every key will be added to the object object. The key bar has another key, value, which is 4. So, it's the same thing as this:

let object = { };

object.a = 4;
Enter fullscreen mode Exit fullscreen mode

But Object.defineProperties() supports adding multiple properties! Remember the interpreter written in JavaScript in the Making an interpreter in Python post? Here's a newer variant:

let i = { };

Object.defineProperties(i, {
  stack: { value: [ ] },
  code : { value: null },
  init : {
    value: function (c) {
      this.i = c.i;
      this.d = c.d;
  }},
  run: {
    value: function () {
      for (let step in this.i) {
        switch (step[0]) {
          case "load": this.stack.push(eval(step[1]));
          case "add":
            let b = this.stack.pop();
            let a = this.stack.pop(); 
            this.run(["load", a+b]);
          case "dump": 
            if (!step[1]) console.log(this.stack.pop());
            else console.log(eval(step[1]));
        }
      }
  }}
});
Enter fullscreen mode Exit fullscreen mode

With this, goodbye and have a good day!

Top comments (0)

In defense of the modern web

I expect I'll annoy everyone with this post: the anti-JavaScript crusaders, justly aghast at how much of the stuff we slather onto modern websites; the people arguing the web is a broken platform for interactive applications anyway and we should start over;

React users; the old guard with their artisanal JS and hand authored HTML; and Tom MacWright, someone I've admired from afar since I first became aware of his work on Mapbox many years ago. But I guess that's the price of having opinions.