When, if ever, would it be a good idea to add or delete properties on an object?

55 views
Skip to first unread message

Inger Hohler

unread,
Jun 21, 2020, 11:12:04 AM6/21/20
to Khan Academy Javascript Technical Q&A
In an effort to learn more about objects I started going though some of the online learning material on W3 schools, and came across references to adding and deleting properties on an object.
https://www.w3schools.com/js/js_object_properties.asp
https://www.w3schools.com/howto/howto_js_remove_property_object.asp

I've read it several times before, but since I wasn't looking for it at the time I did not give it a second thought.

My initial reaction to it now was: Eek! Why would anyone want to use this, because it looks like something that could get you in heaps of trouble and might require lots of extra checks for 'undefined'. Would it not be both easier and better to create the right properties in the first place, and possibly add some booleans to keep track of which properties were active?

I've searched for information about use of this functionality. Although I found several people asking about how to do it, or explaining it, it was not clear to me why they felt a need to add or delete properties after object creation anyway.

Presumably the functionality has been included for a reason, I just cannot think why, and wonder if any of you know.

Thanks in advance!

Larry Serflaten

unread,
Jun 21, 2020, 1:01:24 PM6/21/20
to Khan Academy Javascript Technical Q&A


Inger Hohler wrote:

> Would it not be both easier and better to create the right properties in the first place, and possibly add some booleans to keep track of which properties were active?

There is something to be said for having full control of your environment.  You can easily add and remove items from an array, why should it be different for objects?

That may be part of the reason why the delete command was added to the language.  The language designers could not fathom every possible use of the JS language, so they may have opted to give the programmer more control, rather than less.

You might find their rationale in the specification, if you want to go look for it.  If you want to learn more about how it works, you could read over this material:

The short synopsis is that when variables and functions are created they are given specific attributes.  Some are read-only, some are not, some are deletable, and some are not.  Specifically, variables and functions created in the global scope are created as not deletable.  That means they get the 'dontDelete' attribute.  Variables created at the function scope (like object properties) are created without the 'dontDelete' attribute - they can be deleted.

But again, while its use might be rare, not having that control would mean resorting to the active/not active booleans that you mentioned, which brings with it the possibility of the booleans getting out of sync with their associated properties.  Delete also affects enumerations, looping over the properties (for x in y) where it might be desirable to add and remove properties to control the loops.

I have never used it, so I could not give a practical example, but I can appreciate the designers handing more control over to the programmers, including the responsibility of using it correctly!

I hope this helps!
LFS
 

  

Inger Hohler

unread,
Jun 21, 2020, 2:25:23 PM6/21/20
to Khan Academy Javascript Technical Q&A
Thanks, Larry, that makes sense. The article you pointed me to also had some interesting points about properties. 
I don't think it is something I'll see an occasion to use,  but if I should come across it in a piece of code I'll know a little more about what it does - and the pit falls.

Bob Lyon

unread,
Jun 21, 2020, 4:13:22 PM6/21/20
to Khan Academy Javascript Technical Q&A
The ability to dynamically add properties to an object is incredibly power. So, the same should be concluded about the ability to delete properties, particularly those which the program dynamically added.  Wrt to the Eek! factor, consider the answer to a very popular recurring Help Request at Khan Academy: "How can I tell if both the W and D keys are being pushed simultaneously?"  To that, I'll another: "Which keys are currently being pushed?"  So, we suggest something like
var pressed = {};

keyPressed
= function() {
   
var s = String.fromCharCode(keyCode).toLowerCase();
    pressed
[s] = true; // dynamic addition
};

keyReleased
= function() {
   
var s = String.fromCharCode(keyCode).toLowerCase();
   
delete pressed[s]; // dynamic substaction
};

   
/* Check for two keys being pressed: */
   
if (pressed.w && pressed.d) { ...

Simply use a for - in loop with the pressed object to enumerate which keys are currently being pressed.

I dynamically add properties in a lot of my code.  I have only a few delete instances.  However, I am programming in the small at KA.  I don't konow what best practices would say about all this when programming in the large.

Inger Hohler

unread,
Jun 22, 2020, 11:06:50 AM6/22/20
to Khan Academy Javascript Technical Q&A

Thanks for the example, Bob! Later tonight (for me) I'll try to implement that code, and compare it to how I would have tried to solve the problem without the ability to add or delete properties.That should be interesting!

Inger Hohler

unread,
Jun 23, 2020, 9:39:24 AM6/23/20
to Khan Academy Javascript Technical Q&A
I played with the code on KA https://www.khanacademy.org/computer-programming/skinning-the-cat/6376417946845184
My interpretation of your idea,Bob, and how I'd normally do it. (My first attempt was writing out the loops, which is good practice of one kind. However, for comparison and ease of reading I thought it was better to use more array index methods)
I did not see a quick way to pass the desired characters for the double detection to the function when dynamically adding or removing properties. There probably is one, though. Perhaps I'll find it later.

Larry Serflaten

unread,
Jun 23, 2020, 10:38:48 AM6/23/20
to Khan Academy Javascript Technical Q&A


 Inger Hohler wrote:
What I see used more often is the array method.  Typically they want to test the arrow keys and use 'keyCode' to set the array.  If they need alpha-numeric input, then 'key.code' is the appropriate one to use.

EX:


var keys=[];


keyPressed
= function(){
    keys
[keyCode] = true;
};


keyReleased
= function(){
    keys
[keyCode] = false;
};


fill
(0);
draw
= function() {
    background
(255);
   
   
// typical usage
   
if (keys[UP]){          // move up
        text
("UP", 20, 20);
   
}else if (keys[DOWN]){  // move down
        text
("DOWN", 20, 20);
   
}
   
   
// identify
   
var chars = [];
   
var list = keys.reduce(
                   
function(a, c, i){
                       
if (c){a.push(i);}
                       
return a;
                   
}, []);
   
if (list){
        chars
= list.map(
                   
function(v){
                       
return String.fromCharCode(v);
                   
});
   
}
    text
("Key count: " + chars.length, 20, 50);
    text
("Key values:  " + list, 20, 70);
    text
("Key chars: " + chars, 20, 90);
};
 



Inger Hohler

unread,
Jun 23, 2020, 3:16:45 PM6/23/20
to Khan Academy Javascript Technical Q&A
Thanks, Larry, the array solution without objects is definitely of general interest as an additional way to skin the proverbial cat. And more concise than my last attempt to implement that kind of code. It didn't help that my last attempt also had to deal with forbidden terrain.
 
Many students (I've been there...) try to develop games well before they have an idea of objects. I'm aware that most students will use arrays for this sort of problem, even after they learn to use objects for other things, and also of the difference between using the arrows and the letter keys for program input.  But I thought it would be fun to explore how similar/different the code would be from (my interpretation of) Bob's code, using an array on an object. It was.  Especially since it was objects I was looking into.  Besides, I have a personal interest in using letter keys for input because shortcut keys are kinder on the hands than a mouse :)

I don't know what's "best" in a given situation. The only rule I've tried to adhere to is that easily readable code is better than poorly readable code - but I have discovered that what I consider readable code has changed significantly over time... I do find it attractive that methods can be stored on objects. For a long time, for some reason I though that was only possible to store functions on objects created by constructors - but don't ask me why I thought so. Apart from realizing that object literals and objects created by constructors had some differences, I neither saw anything to support it nor against it.

Larry Serflaten

unread,
Feb 11, 2022, 1:26:38 PM2/11/22
to Khan Academy Javascript Technical Q&A
​This is an attempt to create a code section using three tildes:
​```no indentation
    three spaces indentation
no indentation```

this attempt uses a CODE tag
<code>
no indents
   three spaces
none
</code>


Reply all
Reply to author
Forward
0 new messages