JavaScript Essentials for React Native - #3 Objects, Arrays

JavaScript Essentials for React Native - #3 Objects, Arrays

To master JavaScript, learn to play with objects and arrays

Objects

  • Objects are one of the important data structures in JavaScript.

  • Objects have properties i.e features that define any object.

  • These properties are key-value pairs.

  • Organized /efficient way of storing/accessing data.

  • Not only data, you can also have functions inside an object

  • An object can be created using curly brackets {..}

  • Property names are accessible with dot notation

  • Use for...in to loop over object

Example: Anthony is 26 years old and likes watching cricket. Here, Anthony is an object ( an entity ) and has more properties that define him. We can programmatically define him as :

const person = { 
    firstname: 'Anthony',
    lastname: 'Gonsalves',
    age: 26,
    hobbies: 'Watching cricket',
    greet: function(){
            console.log('My name is ' + this.firstname + ' ' + this.lastname + ' !');
         }
    }; 

console.log(person);
person.greet();

What is this?

  • To access the object, a method can use this keyword.

  • Basically, to get the context of the current object. By having context you can access the object.

  • Arrow functions have no this

Object references and copying

  • Objects are stored and copied "by reference", whereas primitive values: number, string, boolean etc - are always copied "as a whole value"

  • Objects are passed by reference and not by value. This is for efficiency and optimization.

  • Example: To understand this, let's say you have pictures of your last trip. And the total size of files is 5GB. And you want to send these to your friends.

    • The old way is to first transfer these to a physical drive and then give the drive one by one to everyone. And they will copy all the files completely from one drive to their systems.

    • Other way is to upload them to Google Drive, create a shareable link ( address / or a unique reference ). Now everyone can access the content with link address.

      • Creating more copies of the link won't create more images.

      • If anyone deletes content from one link, the same would be reflected in other links too as all point to the same object.

  • A variable assigned to an object stores not the object itself, but its "address in memory" - in other words "a reference" to it.

  • When an object variable is copied, the reference is copied, but the object itself is not duplicated.

      let user = { name: "Rahul" };
    
      let admin = user; // copy the reference
      // two variables: user and admin both point to the same object
    

Comparison by reference:

  • Two objects are equal only if they are the same object.

  •   let x = {};
      let y = x; // copy by reference
    
      console.log( x == y); //true both reference to same object
      console.log( x === y ); // true
    
  • And here two independent objects may look same but are not.

  •   let x = {};
      let y = {}; 
    
      console.log( a == b);  // false
    

Duplicating, cloning, merging

  • Iterate over all properties of object one by one and then create a new object.

  • Or use Object.assign method ( Shallow copy )

  • Use recursion to deep copy

Arrays

  • Commonly used data structure.

  • Arrays are used to store list of items of same or different types, does not matter.

  • Arrays are 0-indexed

  • for...of loop is used to iterate over arrays.

  • Can use in built array methods : forEach(), join(), includes(), push(), pop() etc

// array to store list of books
let listOfBooks = ["Wings of Fire", "5A.M. Club", "The Alchemist", "Zero to One"];
for(book of listOfBooks) {
    console.log(book) // Wings Of Fire /n 5A.M. Club /n The Alchemist ...
}

listOfBooks.pop();
listOfBooks.push("Long walk to Freedom");
console.log(listOfBooks)
console.log(listOfBooks.indexOf("The Alchemist"))

Map, Filter, Reduce

  • map() method is one of the most useful and often used.

  • It calls the function for each element of the array and returns the array of results.

  • Example: We took the list of books, created a list of objects from it, and added a random number less than 100 to each book as the price.

// map function: Used to create a new list of new schema from old list
let listOfBooks = ["Wings of Fire", "5A.M. Club", "The Alchemist", "Zero to One"];
let newList = listOfBooks.map ( (book, index) => { 
                return {id: index, name: book, price: Math.random()*100 }
                });
console.log(newList)
  • filter: to filter the items based on given condition.
let listOfBooks = ["Wings of Fire", "5A.M. Club", "The Alchemist", "Zero to One"];
let newList = listOfBooks.map ( (book, index) => { 
                return {id: index, name: book, price: Math.random()*100 }
                });

// now using filter to filter prices above 50 
const filteredBooks  = newList.filter (book => book.price > 50 )
console.log(filteredBooks)
  • reduce: To calculate a single value from the whole array.

  • In above example, let's say user added above mentioned books to the shopping cart on Amazon. Now you want to calculate the total amount of the shopping cart. You can use a for loop, while loop, map function, forEach function etc to do this.

  • But using reduce function is the simplest here as demonstrated below:

// old list
let listOfBooks = ["Wings of Fire", "5A.M. Club", "The Alchemist", "Zero to One"];
// new list with price details
let newList = listOfBooks.map ( (book, index) => { 
                return {id: index, name: book, price: Math.random()*100 }
                });
let totalPrice = newList.reduce ( (sum, book) => sum + book.price, 0);
console.log(totalPrice)

Conclusion

In this blog, we covered concepts revolving around objects and arrays. These are very important and are building blocks for a React Native developer. Make sure you understand these well.

Thanks for reading!

Resources