Objects In JavaScript ===================== The object is a data structure that stores other data, similar to how an array stores elements. ------------------------------------------------------------------------ ### Objects In JavaScript #### The `object` is a data structure that stores other data, similar to how an array stores elements.
- The object differs in that each `value` stores in an obj is associated with a `key`. ### **The Object** In other programming languages, objects are referred to as, “dictionaries”, “maps”, or “associative arrays”. - Objects are indexed with `keys` instead of numbers. - Order is not guaranteed within an Object. - Objects are defined by using curly braces `{}` - You can think of Objects as tables. #### **Setting Keys and Values** - We assign values to an object by defining the name of the key in brackets and assigning it to a value. > car { color: "Blue", seats: 2 } > "color" in car; true > "model" in car; false - If we try to access a key that has not yet been assigned within an object we will output undefined. - The **preferred method** for checking to see if an object exists at a key is to use the `in` operator. #### **Using Variables as Keys** - It is useful to set a variable as a key because variables can be re-assigned new values — this way we can quickly access different data and also create new key/value pairs. ### Using Different Notations **Dot notation:** - Property identifies can only be alphanumeric (and `_` and `$`) - Property identifiers cannot start with a number. - Property identifiers cannot contain variables. - OK — `obj.prop_1`, `obj.prop$` - Not OK — `obj.1prop`, `obj.prop name` **Bracket notation:** - Property identifiers have to be a String or a variable that references a String. - It is okay to use variables, spaces, and Strings that start with numbers - OK — `obj["1prop"]`, `obj["prop name"]` > let dog = {}; undefined > dog.bark = "Bowowowo"; "Bowowowowo" > dog.bark "Bowowowo" > dog { bark: "Bowowowowo" } - We can also use **dot notation** **“.”** to access key/value pairs in an object. - One thing to note is that when using dot notation, we do not have to use string quotes as the key. #### **Bracket Notation vs Dot Notation** **DotBracket**Easier To ReadYou can use variables as keys! Easier To Write b/c do not need Quotations. Okay to use variables and Strings that start with numbers.Cannot access with VariablesKeys cannot contain numbers as their first character - **When accessing object keys**: Bracket notation needs to refer to that key in quotations, dot notation doesn’t. - **When accessing object keys via a variable**: Bracket notation can refer to that key w/o use of quotations, dot notation can’t do this at all. - As illustrated above, the dot notation cannot access a variable key — since it takes a **literal** interpretation of the key. You can put an object together in a single statement. let myDog = { name: "Fido", type: "Doge", age: 2, favoriteToys: ["bone", "ball"], }; #### **Operator Precedence Revisited** - The concept of Operator Precedence also applies to objects. - There are two types of associativity: - `Right Associativity` : When code is evaluated right to left. a = b = 1; - Since **assignment of variables** takes lowest precedence, we end up evaluating b = 1 first before a = b. - `Left Associativity` : When code is evaluated left to right. let id = "header"; let element = document.getElementById(id).value; - We first resolve the document variable, then use dot notation to retrieve the getElementById function, we eval it's arguments, access it's value, and then retrieve assignment \(the lowest precedence\). ### Iterating Through Objects Because objects store **unordered** key-value pairs, we do not rely on indices to access values; instead, we rely on our keys. #### **A New Kind of For Loop** > SYNTAX: for (let variable in object) {statement}; - We use a special syntax to iterate through each key of an object called a `for-in loop`. #### **Methods vs Functions** A `Method` is a function that belongs to an object. Every method is a function, but not every function is a method. myFunc is a function myObject.myFunc is a method of the object myObject myObject["myFunc"] is a method of the object myObject - **Methods** are just a key-value pair where the **key is the function name and the value is the function definition**. - To invoke these methods we just need to specify which object is calling that method. myObject.methodName(); #### **Useful Object Methods** - `Object.keys()` : A method that allows us to iterate through keys, it accepts an obj as the argument and returns an array of the keys. - `Object.values()` : Method that accepts an object as the argument and returns an array of the values. #### **Iterating through an Object’s keys & values** - `Object.entries` : Method that accepts an object as the argument and returns an array of the \[key, value\] pairs within. > Object.entries(cat)[['name', 'Freyja'], ['color', 'orange']] ### References vs Primitives #### **Primitives vs Objects** So far we have learned about 6 different data types: - **Primitive**: Boolean, Null, Undefined, Number, String. - **Reference**: Object (Arrays are a type of object) - Remember that **primitive** types are immutable! #### **Immutability** - When we reassign primitives we simply have our variable point elsewhere in memory. - In a nutshell, **immutability** cannot change values in memory, but only reassign where our variables are pointing to. #### **Mutability** - If we change either cat1 or cat2, our computer memory will change because they are both pointing at the same memory location. ### Rest and Spread #### **Using the Spread Operator and Rest Parameter Syntax** **Accepting Arguments** - Just keep in mind that the function will still run even if it is not passed any arguments. - Parameters will take just as many arguments as they need even if more than enough is offered. - We will encounter an error if there are not enough parameters ( > 0). #### **Utilizing Rest Parameters** - `Rest Parameter Syntax` : Allows us to capture all of a function's incoming arguments into an array. - Only the last parameter can be a rest parameter. #### **Utilizing Spread Syntax** - **Spread Operator**: This allows us to break down a data type into the elements that make it up. - Takes a data type (i.e. array, obj) and spreads the values of that type where elements are expected. - Takes iterable data and spreads the elements of that type where arguments are expected. let numArray = [1, 2, 3]; // here we are taking `numArray` and *spreading* it into a new array where // comma separated elements are expected to be let moreNums = [...numArray, 4, 5, 6]; > moreNums // => [1, 2, 3, 4, 5, 6] **With Objects** ------------------------------------------------------------------------ ### Learn More On My Blog: Web-Dev-Hub
Memoization, Tabulation, and Sorting Algorithms by Example Why is looking at runtime not a reliable method of…bgoonz-blog.netlify.app
By Bryan Guner on [May 27, 2021](https://medium.com/p/b212486dade6). Canonical link Exported from [Medium](https://medium.com) on August 31, 2021.