+ 15
Associative arrays: JS object vs. Python dictionaries
In practice, besides the ability to add methods to a JS object, what are the differences between using a JS object and a Python dictionary to store and retrieve named values? I can think of a couple (see below), but are there others? - slicing is not possible on a JS object [edit: slicing is not actually an operation on any dictionary or map, JS or other. I remembered my Python incorrectly.] - an instance of a JS object cannot have more/new (nor less) named values than the defined object, while Python dictionaries are dynamic
22 ответов
+ 16
2. I wasn't quite clear about your reference to not being able to dynamically add name/value pairs to Javascript objects.
You are able to dynamically add new pairs directly to the object or any part of the prototype chain using either approach:
let dict = {"a":123, "b":"test"}
dict.c = "foo"
dict["d"] = "bar"
This object would contain the following 4 sets of name / value pairs:
"a" : 123
"b" : "abc"
"c" : "foo"
"d" : "bar"
Were you referring to something different?
+ 12
Might find a clear answer here:
https://stackoverflow.com/a/20988172
And i why do you mean by "the ability to add methods to a JS object"?
+ 11
David Crowley Interesting question.
I'd be interested in exploring this further for a better understanding for myself. 😉
A few questions come to mind though regarding your original question.
1. I believe you are correct in that no native slice() method for objects exist in Javascript. Even if the JS object is an Array, the slice() method only applies to array items stored via positional indexes, not named indexes.
That said, I thought this was the case for Python dictionaries as well. While Python Lists can splice using [start:stop:increment] notation or the slice() function, I wasn't aware of this applying to Dictionary objects.
If I'm correct, then slicing can be implemented in both Javascript objects and Python dictionaries via some looping mechanism be they imperative or functional.
(Continued...)
+ 10
All said, Javascript does have an Associative Array, the Map object.
This addresses all the issues I mentioned and much more.
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Map
I suspect that is what Wikipedia is referring to with a native data type.
Regarding the JS lesson... I just reviewed that link and agree there are some inaccurate statements that could be reworked. However, that's handle by another group within SoloLearn. I'm just a lowly moderator serving the community. 😉
+ 9
David Crowley I'm glad to help... especially when it's for the purpose of gaining a deeper understanding of a language.
Also, it's questions like this that help me to dig deeper for my own clearer understanding.
So... thank you for asking such a good question. Also, feel free to tag me on similar questions in the future if you think I can help. 😉👌
+ 8
David Crowley We must have posted around the same time. I completely missed your followup questions.
1. It's not so much about adding properties to a class, Object class or any classes. Rather, it's adding properties to object instances. In Javascript, binding new members to object instances doesn't break classes as classes are really syntactic sugar for function prototypes.
Since everything in Javascript is an object, including functions, all objects can be extended the same way.
2. It's tempting to say, if it walks, talks, and looks like a duck, it's likely a duck. 😉 However, I think what makes it fall short compared to other languages are as follows:
- Keys are stored only as strings.
- Elements aren't iterable.
- Element count isn't available via property or method.
- Object prototype properties could collide with a key causing unintended outcomes.
(Continued...)
+ 8
David Crowley Ah...You must be going through the courses and that's why you're asking these questions.
Sadly, I barely read much of the content and just blew through the questions.
I will say that MDN is my preferred resource for such clarifications. That... and good old code writing and stepping through the code dsbugger. 😉
+ 7
David Crowley
Mind giving an example?
and by "we can also define methods on them." you mean prototyping?
https://code.sololearn.com/Ww0mwTKKlqcH/?ref=app
+ 6
Indeed... ES6 was a much long overdue improvement for Javascript. Prior to 2015, Javascript was tolerable to work with and just unbearable prior to 2007'ish or so.
+ 5
David Carroll I think i was mistaken about slices on dictionaries after i went back to check. Works on standard arrays, but not named key:value pairs.
+ 5
Burey that is a nice bit of code that uses features beyond my knowledge base. I will enjoy unpacking that!
+ 5
David Crowley If learning on a desktop is an option, I highly recommend you stop trying to learn using your phone and certainly stop using Code Playground.
Working within a desktop browser, preferably Chrome, with the console within Developer Tools is by far the optimal way to learn.
I highly suggest working within an IDE with debugging capabilities to step through code while executing line by line, loop by loop, stack by stack. You can see the variables within global, local, and closure scopes, you can manipulate values during a specific line of execution, you can execute new statements from within that point.
This will give you instant access to everything going on that is accessible for a developer to manipulate.
[UPDATE]
The above mentioned debugging capabilities are available in both an IDE and Dev Tools.
Also, I recommend either VS Code or Jetbrains PHPStorm or WebStorm for web debugging.
+ 4
David Carroll your answer to 2. - like Burey's link to the Stack Overflow thread - showed me that objects can not only be initialized like that but added to later in the same way (literal, method notation, array notation). The main difference between Python and JS is that no matter what you type as a key, it is automatically stored as a string in JS whereas it can be a number of types in Python.
It leads to a couple other questions:
1. is this way of adding properties (key:value pairs in this usage case) exclusive to the Object class in JS or a capabiliy built into all JS classes?
2. These answers make it seem like the JS Object class is very much an associative array, so why does the course set it up as if it isn't? https://www.sololearn.com/learn/JavaScript/1242/
The *ahem* unquestionable wikipedia page on associative arrays/mapping includes JS as a language that includes them as a native data type.
3. Should I post these questions separately, in new threads?
+ 4
David Carroll A clarification: Maps were only introduced in ES6, so are not part of older code (pre 2015). Ignoring the newer Map data structure (also Set, WeakMap and WeakSet) though, I think that simple Objects are still Associative Arrays with the keys constrained to strings. [edit: ... and the other three limitions you mentioned. Needing homebrewed functions and additional data structures to get the number of properties using the .keys() or .values() methods is a serious drawback.]
+ 3
Burey I mean that objects can have attributes/ properties (the part that we use when JS objects imitate associative lists) and methods (functions that can be used on the object). Since we use general objects in JS as key:value pairs, we can also define methods on them. In other languages, the associative list data types (like Python dictionaries) are predefined and we can't define new methods for them.
+ 3
In python I have seen that it is also possible to define functions in dictionary but not sure if it recommended acording to zen thingy!
+ 3
Well persistence pays off: the SoloLearn course does eventually present Map (in the ES6 module) and makes a pretty clear comparison with Object.
Quote:
"An Object is similar to Map but there are important differences that make using a Map preferable in certain cases:
1) The keys can be any type including functions, objects, and any primitive.
2) You can get the size of a Map.
3) You can directly iterate over Map.
4) Performance of the Map is better in scenarios involving frequent addition and removal of key/value pairs.
"
It just doesn't explicitly mention or refer back to what it previously said about associative arrays.
https://www.sololearn.com/learn/JavaScript/2980/
+ 3
David Carroll I am a fairly novice programmer, but I am definitely at the point where I find tutorials insufficient to really grasp the languages. I assume they are meant as quick start +. I use the code playground often to test concepts I don't feel I grasp, and that is an excellent way to see if changing specific things has the expected outcome. Burey's code in this thread seems like an example of someone who has a deeper understanding of the entire JS framework. I appreciate you bringing MDN into it. That is the next step.
Cheers!
+ 2
https://code.sololearn.com/chJU8ziKaTaE/?ref=app
[EDIT: by David Carroll]
Hi Elie Aro ... You may not be aware, but posting messages like this in a thread with no relevance to the discussion is considered spam and can lead to action taken against one's account.
Please limit advertising to posts that are already designated for such sharing.
Please delete this and any other messages from unrelated threads when you see this message.
Thanks for your understanding. 🙏
+ 2
Burey after all my thinking, I can finally answer your question 'by "we can also define methods on them." you mean prototyping?'
That is not what I meant when I wrote the post. I now think that at that time I was confusing both Object with classes and declarations/definitions with instances. Having dug into the reference documentation, I see that prototyping is how you would literally have to implement what I wrote on an Object to affect each instance of the Object. I didn't know what prototyping was. I was only aware of initializing an Object with constructors and methods. I don't think you can initialize a new Python dictionnary (or JS Map) by specifying constructors and methods... But I am certainly open to learn if they are!