Skip to content

Instantly share code, notes, and snippets.

@tech-chieftain
Created January 13, 2023 20:02
Show Gist options
  • Save tech-chieftain/0e3fd5fcbe3e337883bdb38584971239 to your computer and use it in GitHub Desktop.
Save tech-chieftain/0e3fd5fcbe3e337883bdb38584971239 to your computer and use it in GitHub Desktop.
Objects Discussion

Object Discussion Questions

There is some coding in this discussion. Feel free to write them in a REPL or in the comments below.

  1. How is an object different from an array?
  2. How does const work with objects?
  3. Explain the difference between bracket syntax and dot syntax. Give an example of something that works with bracket syntax but not dot syntax. Give an example of something that works with dot syntax but not bracket syntax.
  4. What are computed properties? Write an example code.
  5. What is the difference between Object.keys and Object.entries? Write example code using both of them.
  6. How do we get only the values of an object?
@a-aidah
Copy link

a-aidah commented Jan 14, 2023

  1. difference is An Array is a collection of data and a data structure that is stored in a sequence of memory locations.
    While an object is a collection of properties, and a property is an association between a name (or key) and a value.

1.The const keyword makes a variable itself immutable, not its assigned content. When the content is an object, this means the object itself can still be altered. Therefore, it's possible to change the content of the object that is declared with const variable, but you cannot assign a new object to a const variable.

  1. Only with bracket notation we can access object properties using variable: Example Object[variable] this help dynamically accessing properties like looping and assigning computed properties
    dot notation is more readable and easier. You can directly access properties by calling the key : Example Object.key //will return value

  2. Computed properties use an expression in brackets []. Then use the result of the expression as the property name of an object.
    an example would be:
    let x = "age";
    Const person={
    name : "Ahmed",
    [x] : 24,
    }

4.Object.keys will return keys of object inside an array example: Object.keys(object) = ["key1", "key2"]
Object.enteries will return each both keys and values inside an array example Object.entries(object) = [ ["key1","value1"], ["key2","value2"] ]

  1. The Object.values() static method returns an array of a given object's own enumerable string-keyed property values.

@Abrar-Abdulwahed
Copy link

Abrar-Abdulwahed commented Jan 14, 2023

0: 🟢Array vs Object:
arrays:

  • used whenever we want to create and store a list of multiple items in a single variable, useful when creating ordered collections.
  • elements accessed by numerical position (0-based indexing)
  • iterated by for, forEach.

object:

  • used whenever we represent anything that is made up a set of characteristics, consists of key/value pairs.
  • elements accessed by key using don or bracket notations.
  • iterated by for, forEach, for..in, for..of.

1: 🟢const:
one way of restricting objects, in which a way that reference is immutable but content(key or value) is mutable.


2: 🟢Dot vs Bracket Notation:

1. dot:

  • property identifies can only be alphanumeric (and _ and $), ex: obj.prop, obj.prop_1, obj.prop$
  • properties identifiers can’t start with a number. ex: obj.1prop
  • properties identifiers can’t contain a space obj.prop name
  • property identifiers cannot contain variables.

2. bracket:

  • property identifies can be String (alphanumeric and spaces, or can start with numbers),
    ex: obj["prop_name"], obj["prop name"], obj["1 prop"]
  • property identifiers can be a variable that references a String.
    ex:
let obj = {
      cat: 'meow',
      sheep: 'baa'
  };
let goats = 'sheep';
let sound = obj[goats];
console.log(sound); //baa

3: 🟢Computed Properties:
This feature allows for dynamic names that calculated at runtime.

  1. let us to use an expression inside brackets [].
    For example:
 const codes = { Yemen: "967", "Saudi Arabia": "966"}
 const student = {
        name: "Abrar",
        major: "Web Development",
        [`phone_${codes.Yemen}`]:  "777-777-777",
        [`phone_${codes["Saudi Arabia"]}`]:  "56-777-7777",
 }
 console.log(student .phone_966); // 56-777-7777
  1. or can use this feature for using variable as property name of an object.
    For example:
  function initNewObject(key, value) {
      return {
            [key]: value
      }
  }
  console.log(initNewObject("name", "Abrar")) // {name: "Abrar"}

4: 🟢Object.keys vs Object.entries:

Object.keys():

  • used with (array-like objects, objects).
  • return an array of a given object's property names.
  • For example:
        // Array
        const arr = ["Abrar", "Jehad", "Sarah"];
        console.log(Object.keys(arr)); // ['0', '1', '2'] =>because arrays are 0-based indexing
    
        // Array-like object
        const arr_like_obj = { 0: "a", 1: "b", 2: "c" };
        console.log(Object.keys(arr_like_obj)); // ['0', '1', '2'] 
        
        // Array-like object with random key ordering
       // When using numeric keys, the keys are returned in the numerical order
        const anObj = { 100: "a", 2: "b", 7: "c" };
        console.log(Object.keys(anObj)); // ['2', '7', '100']
    
       // object with string keys
        const obj = { name: "Abrar", bootcamp: "FEW"};
        console.log(Object.keys(obj)); // ['name', 'bootcamp']

Object.entries():

  • used with (arrays, array-like objects, objects).
  • return an array of [key, value]'s objects.
  • For example:
      // Array
      const arr = ["Abrar", "Jehad", "Sarah"];
      console.log(Object.entries(arr)); // [ ['0', 'Abrar'], ['1', 'Jehad'], ['2', 'Sarah'] ]
    
      // Array-like object
      const arr_like_obj = { 0: "a", 1: "b", 2: "c" };
      console.log(Object.entries(arr_like_obj)); // [ ['0', 'a'], ['1', 'b'], ['2', 'c'] ]
      
      // Array-like object with random key ordering
      // When using numeric keys, the output are returned in the keys' numerical order
      const anObj = { 100: "a", 2: "b", 7: "c" };
      console.log(Object.entries(anObj)); // [ ['2', 'b'], ['7', 'c'], ['100', 'a'] ]
    
     // object with string keys
      const obj = { name: "Abrar", bootcamp: "FEW"};
      console.log(Object.entries(obj)); // [ ['name', 'Abrar'], ['bootcamp', "FEW"] ]

5: 🟢How do we get only the values of an object? Object.values().


References:

  1. mdn
  2. meduim
  3. Me 👨‍💻

@Haneen-Abdulgllil
Copy link

How is an object different from an array?

  • Objects represent a special data type that is [mutable] and can be used to store a collection of data (rather than just a single value).

  • Arrays are a special type of variable that is also mutable and can also be used to store a list of values.

How does const work with objects?

The const keyword makes a variable itself immutable, not its assigned content. When the content is an object, this means the object itself can still be altered.
Therefore, it's possible to change the content of the object that is declared with const variable, but you cannot assign a new object to a const variable.

Explain the difference between bracket syntax and dot syntax. Give an example of something that works with bracket syntax but not dot syntax. Give an example of something that works with dot syntax but not bracket syntax.

When you use dot notation, key means the actual property in the object, which will not be there. So, undefined is returned which is not equal to true.
When you use [] notation you are accessing the property in the object with the name in the variable key. So, that will work.
For example,

var myObj = {
    myVar : 1
};

for (var key in myObj) {
    console.log(key);
    console.log(myObj.key);
    console.log(myObj[key]);
}

This will print,

myVar
undefined
1

What are computed properties? Write an example code.

allows you to use an expression in brackets []. It’ll then use the result of the expression as the property name of an object.
For example:

let Name = 'haneen';

const rank = {
  a: 1,
  b: 2,
  [Name]: 6,
};

console.log(rank.haneen); // 6

What is the difference between Object.keys and Object.entries? Write example code using both of them.

[Object.keys] returns only the own property names.

[Object.entries] returns an array of arrays with key and value.

 let user = {
 name: "haneen",
 age: 29
};

Object.keys(user) = ["name", "age"]

Object.entries(user) = [ ["name","haneen"], ["age",29] ]

How do we get only the values of an object?

To access the properties of an object without knowing the names of those properties you can use a for ... in loop:

for(key in data) {
    if(data.hasOwnProperty(key)) {
        var value = data[key];
        //do something with value;
    }
}

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment