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?
@MohdBasurra
Copy link

Answer 1
An object is a collection of key-value pairs, while an array is an ordered list of values
Objects are more flexible than arrays

Answer 2
it prevents the object from being reassigned to a different value. but the properties of the object can still be changed

Answer 3
Bracket syntax is used to access properties of an object using a string.

Answer 4
Computed properties are properties in JavaScript objects that are dynamically calculated based on other properties. They are useful for creating dynamic objects that can be used in a variety of situations.

Answer 5
Object.keys returns an array of a given object's own enumerable property names, whereas Object.entries returns an array of a given object's own enumerable string-keyed property [key, value] pairs.

Example code using Object.keys:

const person = {
name: 'John',
age: 25,
job: 'engineer'
};
const keys = Object.keys(person); // returns ['name', 'age', 'job']
console.log(keys);

Example code using Object.entries:
const person = {
name: 'John',
age: 25,
job: 'engineer'
};
const entries = Object.entries(person); // returns [['name', 'John'], ['age', 25], ['job', 'engineer']]
console.log(entries);

Answer 6
To get only the values of an object, you can use the Object.values() method. This method returns an array containing all the values of the object's own enumerable properties.

@dhiashalabi
Copy link

  1. An object is a collection of properties, and a property is an association between a name (or key) and a value. A property's value can be a function, in which case the property is known as a method. In contrast, items stored in an array are ordered, and each item can be accessed by its index number.
  2. const is a signal that the identifier won't be reassigned. It doesn't mean the value it holds is immutable, just that the variable identifier can't be reassigned. For instance, in the case of objects, this means the object's contents (e.g., what is stored in the object) can be altered.
  3. Dot syntax is used to access properties of an object. Bracket syntax is used to access properties of an object when the property name is stored in a variable. Dot syntax does not work with bracket syntax, but bracket syntax works with dot syntax. For example, the following code uses dot syntax to access the property name of an object: const obj = { name: 'John' }; console.log(obj.name); // John // The following code uses bracket syntax to access the property name of an object: const obj = { name: 'John' }; const key = 'name'; console.log(obj[key]); // John
  4. Computed properties are properties whose keys are computed dynamically. For example, the following code uses a computed property to add a property to an object:
  • const obj = { [key]: value }; obj[key] = value; console.log(obj);
  • { key: value }
  • The key is computed dynamically.
  • The value is the same as the key.
  • The key is stored in the variable key.
  1. Object.keys returns an array of a given object's own enumerable property names, in the same order as that provided by a for...in loop. Object.entries returns an array of a given object's own enumerable string-keyed property [key, value] pairs, in the same order as that provided by a for...in loop. The only important difference is that a for...in loop enumerates properties in the prototype chain as well.
  2. Object.values returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop. (The only difference is that a for...in loop enumerates properties in the prototype chain as well.)

@nabily4e-dev
Copy link

nabily4e-dev commented Jan 14, 2023

0 - An object is a collection of key-value pairs, where each key is a string or symbol and each value can be any data type. An array, on the other hand, is an ordered collection of values, where each value can be of any data type, and the values are accessed by index number.

1- In JavaScript, const is used to create a variable that cannot be reassigned. When used with objects, the object itself cannot be reassigned to a new value, but the properties of the object can still be modified.

2 - Bracket syntax and dot syntax are used to access properties of an object. Bracket syntax is used when the property name is a variable or is not known until runtime. Dot syntax is used when the property name is known and is a valid identifier.

Example of something that works with bracket syntax but not dot syntax:

Copy code
const obj = {
"property name": "value"
}
console.log(obj["property name"]) // "value"
console.log(obj.property name) //error

Example of something that works with dot syntax but not bracket syntax:

Copy code
const obj = {
propertyName: "value"
}
console.log(obj.propertyName) // "value"
console.log(obj["propertyName"]) // "value"

3 - Computed properties are properties that are defined using expressions, rather than fixed property names. This allows for dynamic property names that are calculated at runtime.

function createObject(key, value) {
return {
[key]: value
}
}
console.log(createObject("propertyName", "value")) // {propertyName: "value"}

============================================

let fruit = prompt("Which fruit to buy?", "apple");

let bag = {
[fruit]: 5, // the name of the property is taken from the variable fruit
};

alert( bag.apple ); // 5 if fruit="apple"

4 - Object.keys() is used to return an array of the object's own enumerable property names, whereas Object.entries() is used to return an array of the object's own enumerable property [key, value] pairs.

Copy code
const obj = {
key1: "value1",
key2: "value2"
}
console.log(Object.keys(obj)) // ["key1", "key2"]
console.log(Object.entries(obj)) // [["key1", "value1"], ["key2", "value2"]]

5 - To get only the values of an object, you can use the Object.values() method which returns an array of a given object's own enumerable property values, in the same order as that provided by a for...in loop.

Copy code
const obj = {
key1: "value1",
key2: "value2"
}
console.log(Object.values(obj)) // ["value1", "value2"]

@ShadyAlmuraish
Copy link

0- an object resembles many existing physical objects in life in terms it has properties and functions array was restricted to storing the same type but here in javascript it allows to the storage of different types.
1-it just make them un able to be modified.
2- Square bracket notation allows the use of characters that can't be used with dot notation. var foo = myForm.foo[]; // incorrect syntax
var foo = myForm["foo[]"]; // correct syntax.
3. Computed properties are labels that change based on the code
4. Object.keys shows you just the labels and Object.entries shows you the labels and the values
5. To only see the values, you can use Object.values method.

@iiAbady
Copy link

iiAbady commented Jan 14, 2023

  1. Array is a special kind of an object. Array is collection of different data types. Any variable can be an object. Object is an ordered collection of key-value pairs. Array are created with [] and (), Object are created with {}, ().
  2. Because when we create const object we can then add or change new properties.
  3. Dot syntax are used when our key is named without letters like '-' and bracket syntax are used when we want to add these letters. Like object["first-letter"] and object[first-letter].
  4. const math = {
    add: (x, y) => x + y,
    subtract: (x, y) => x - y,
    multiply: (x, y) => x * y,
    divide: (x, y) => x / y
    };

const x = 10;
const y = 5;

const results = {
[add of ${x} and ${y}]: math.add(x, y),
[subtract of ${x} and ${y}]: math.subtract(x, y),
[multiply of ${x} and ${y}]: math.multiply(x, y),
[divide of ${x} and ${y}]: math.divide(x, y)
};
console.log(results);
4. Object.keys returns keys of an object, Object.entries returns both keys and values.
5. Object.values()

@HamadBakeel
Copy link

  1. Objects represent “things” with characteristics (aka properties), while arrays create and store lists of data in a single variable.

  2. The const declaration creates a read-only reference to a value. It does not mean the value it holds is immutable—just that the variable identifier cannot be reassigned. For instance, in the case where the content is an object, this means the object's contents (e.g., its properties) can be altered.

  3. The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.
    An example of something that works with bracket syntax but not dot syntax is accessing an object’s property by its index in an array. For example, if you have an array of objects, you can access the first object’s property using bracket syntax like this: myArray[0].propertyName. This would not work with dot syntax.
    An example of something that works with dot syntax but not bracket syntax is accessing an object’s method by its name. For example, if you have an object with a method called “doSomething”, you can call it using dot syntax like this: myObject.doSomething(). This would not work with bracket syntax.

  4. computed property is one that runs some code in order to calculate the value.
    struct Person {
    var name = "Taylor"
    var favoriteColor = "red"
    var favoriteCity = "Tokyo"
    var favoriteFood = "tea"

    var greeting: String {
    return "Hello, my name is (name), and I like (favoriteFood), (favoriteCity), and the color (favoriteColor)."
    }
    }

  5. Object. keys() method returns only the own property names and it only works for ES5 while Object. entries() method returns an array of arrays with key and value and it works from ES6
    var object = {
    2: 'Geeks1',
    23: 'Geeks2',
    52: 'Geeks3'
    };
    let valuesArray = Object.keys(object);
    for (let value of valuesArray) {
    document.write(value + "
    ");
    }

  6. Object.value(objectName);

@SufyanCS
Copy link

0- An object is a collection of properties, while an array is an ordered list of values. Objects are used to store keyed collections of various data and more complex entities, while arrays are used to store lists of values and can be accessed by index. Objects use key-value pairs to store data, while arrays use numbered indexes.

1- Const works with objects by making the object immutable, meaning that it cannot be changed or reassigned. This helps to ensure that the object remains consistent and secure. It also prevents accidental changes to the object.

2- The dot notation is used mostly as it is easier to read and comprehend and also less verbose. The main difference between dot notation and bracket notation is that the bracket notation allows us to access object properties using variable.

3-computed property is one that runs some code in order to calculate the value.
Ex:
struct Person {
var name = "Taylor"
var favoriteColor = "red"
var favoriteCity = "Tokyo"
var favoriteFood = "tea"

var greeting: String {
    return "Hello, my name is \(name), and I like \(favoriteFood), \(favoriteCity), and the color \(favoriteColor)."
}

}

4- Object.keys is a method that returns an array of a given object's own enumerable property names, whereas Object.entries is a method that returns an array of a given object's own enumerable property [key, value] pairs.

Example code using Object.keys:

let obj = {name: 'John', age: 25};
let keys = Object.keys(obj);
console.log(keys); // Output: ['name', 'age']

Example code using Object.entries:
let obj = {name: 'John', age: 25};
let entries = Object.entries(obj);
console.log(entries); // Output: [['name', 'John'], ['age', 25]]

5- To get only the values of an object, you can use the Object.values() method. This will return an array containing all the values of the object's own enumerable properties

@YassinAbdulrahman
Copy link

0- object represent real worlds entities and their properties like cars and their properties like color model and so on . Is collection of keys and values, On the other hand, an array is a collection of items that are ordered and indexed by their position and Each item in an array can be of any data type and is accessed by its index ,which is a number starting from 0 .

2- using const with objects will prevent you from reassigning the variable to a new object, but it will not prevent you from modifying the properties of the object.

3- const obj = {
firsname: "room 3 ",
'last-name': "wiinng",
}

console.log(obj["last-name"])
console.log(obj.last-name)

  • Bracket notation uses square brackets [] we use it when the property name contains special characters or spaces, and the property is not known.
  • On the other hand, dot notation uses the dot , we use it when does not contain special characters or spaces.

onst fruits = ['apple', 'banana', 'orange'];
const fruitObject = {
[fruits[0]]: "red",
[fruits[1]]: "yellow",
[fruits[2]]: "orange"
}
console.log(fruitObject);

4- Object.keys dynimic naming
Object.entries give the hole thing in an array

5-obj.values

@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