In this blog, I will write on my learnings from the Eloquent Javascript Book's Chapter 4: Data Structures: Objects and Arrays.
Here's the PDF for Eloquent Javascript Book's Chapter 4.
TOC:
- Arrays
- Objects
-
How to access properties and methods of values in JavaScript ?
- Dot property accessor
- Square brackets property accessor
- in Operator
- Object.keys() and Object.assign()
- Mutability
- Different Ways to loop through an Array
- Rest Parameter & Spread operator (...)
- JSON
Arrays
-
First, let's think of what are array's in real world.
- A Pile of books: You have a pile of books and a rack with multiple layers. Once all the books are arranged, you essentially created an array of elements (in this case, arrays of books).
- Numbered points mentioned in the TOC: All the points described above are in an ordered series of sequence, so essentially, so we create an array (of 7 elements).
A array is a variable that can store multiple values. Those values are accessed using a numbered indexing. An array is created with a pair of square brackets
[]
.-
Syntax: Declaring an array
let array_name = [item1, item2, ...]; // Declaring an array
-
You can assign values when creating the array by including them in between the square brackets
[]
, with commas,
separating the values. The values in an array can be accessed by writing the name of the array followed by an index position with the following syntax :
let name = array_name[indexValue]; // Accessing Array Elements
Arrays are zero indexed, meaning the first item in an array will have an index of 0, the second item’s index will be 1, and so forth.
-
Arrays are special kinds of objects in Javascript
typeof [1, 2, 4]; //'object'
Also, that's why we can have variables of different types in the same array
Objects
- Think about objects in the non-programming sense, like a car. A car can have different colors, they are manufactured by different people, with different companies, with different fuel type and many other properties.
- Object-oriented programming (OOP) is a way to write programs using objects. Object-oriented programming is nothing but the capability to represent any real world object (real object with any object that you can see through a naked eyes).
- So, in programming terminologies object is another variable that allows us to store multiple pieces of data. Allow you to “group” related data together and split your code into logical pieces.
-
Syntax:
let objectName = { key: value, key: value, };
Order of properties doesn't matter in an object.
An object is declared using curly braces
{}
. Properties and their values are stored within the curly braces, separated by a colon(:)
. Each property is separated by a comma(,)
, which comes after each property’s value. Each property is a key/value pair. Objects use named indexes.It is also possible to assign a value to a property with the
=
operator. This will replace the property’s value if it already existed or create a new property on the object if it didn’t.-
To delete an object in JavaScript we use
delete
operator. It deletes both the value of the property and the property itself. For Example,
const Car = { carname: 'ABC', carno: 1234 }; delete Car["carname"]; //OR (both are valid) delete Car.carname;
But, the difference between setting a property to undefined and actually deleting is that, in the first case, the object still has the property (no value), whereas in the second case the property is no longer present.
How to access properties and methods of values in JavaScript ?
- First of all, What are properties and methods?
- As we know everything in JavaScript is an object and an object is a collection of properties so almost all JavaScript values have properties except are null and undefined.
-
If we try to access a property on one of these nonvalues, you get an error. For Example:
null.length; // → TypeError: null has no properties
A property's value can be a function, in which case the property is known as a method.
-
So, the two main ways to access properties in JavaScript are with a dot and with square brackets.
- Dot property accessor
-
When using a dot, the word after the dot is the literal name of the property(identifier).
let hero = { name: 'Batman' }; hero.name; // 'Batman'
You can also use the dot property accessor in a one after another to access deeper properties:
object.prop1.prop2
.Choose the dot property accessor when the property name is known to us because it takes the literal meaning of the Identifier.
-
Javascript identifier only contains Unicode letters,
$
,_
, and digits0..9
, but cannot start with a digit and therefore we can't access arrays using dot notation. For example:
books.3; // SyntaxError: Unexpected number
Square brackets property accessor
When using square brackets, the expression between the brackets is evaluated to get the property name.
Choose the square brackets property accessor when the property name is dynamic (when we don't know the property name).
-
But what if we have key which has spaces or special character such as
(-)
. So, to access the properties with these special names, use the square brackets property accessor.
let descriptions = { work: "Went to work", "touched tree": "Touched a tree" }; console.log(descriptions."touched tree"); // SyntaxError: Unexpected string console.log(descriptions["touched tree"]); // "Touched a tree"
in Operator
- The
in
operator returns booleantrue
if the specified property is in the specified object, array or a string. -
For Example:
var person = { firstName:"Prerana", lastName:"Nawar" }; console.log("firstName" in person); //true
Object.keys() and Object.assign()
- The
Object.keys()
method returns an array of a given object's keys. The ordering of the properties ( elements in an array ) is the same as that of given objects. -
For Example:
const object = { firstName : 'Prerana', rollNo : 09, student : true }; console.log(Object.keys(object)); // ["firstName", "rollNo", "student"]
-
We can also run this function with an array. For example,
const array = ['car', 'pencil', 'pen']; console.log(Object.keys(array)); // ['0', '1', '2']
The
Object.assign()
function that copies all properties from one object into another.-
For Example,
const obj1 = { a: 1, b: 2 }; const obj2 = { b: 4, c: 5 }; const result = Object.assign(obj1, obj2); console.log(obj1); // { a: 1, b: 4, c: 5 } console.log(result); // { a: 1, b: 4, c: 5 }
Mutability
- Mutable is a type of variable that can be changed. In Javascript only objects and arrays are mutable.
- A mutable object is an object whose state can be modified after it is created.
- Immutables are the objects whose state cannot be changed once the object is created. Strings and Numbers are Immutable.
- When comparing two object, JavaScript compares internal references which are equal only when both operands refer to the same object in memory, keys and values are not checked, so the content of the object doesn't matter, the operands both have to reference the same object to return true in a comparison.
-
So, Objects and Arrays can't be compared using Equality Operators like we do with Strings. Two objects are never the same even if they have the same content, as two different instances of Object is never equal.
-
With Objects:
const person1 = {name: 'Prerana'}; const person2 = {name: 'Prerana'}; person1 === person2 //false
-
With Objects:
const names = ['Prerana','Siddhi']; const name1 = ['Prerana','Siddhi']; names === name1 //false
-
-
But, when we have two references to the same object they are similar. For example,
const person1 = {name: 'Prerana'}; const person2 = person1 person1 === person2 // true
Different Ways to loop through an Array
-
The legendary for loop:
var array = ["Hello","World","Good","Morning"]; for (var i = 0; i < myStringArray.length; i++) { console.log(myStringArray[i]); }
-
Using forEach() function:
const array = ["one", "two", "three","four"] array.forEach(function (item, index) { console.log(item, index); }); // Using Arrow Functions array.forEach(item => console.log(item));
-
Using ES6 for-of statement:
const array = ["one", "two", "three","four"] for (const number of array){ console.log(number); }
Rest Parameter & Spread operator (...)
- The spread operator allows us to spread the value of an array or we can say that an expression to be expanded in places where multiple arguments are expected.
-
For Example:
let numberArray = [0, 1, 2]; let newNumber = 12; numbers = [...numberArray, newNumber]; // numbers : [0, 1, 2, 12]
-
For Example 2:
function multiple(x, y, z) { return x * y * z; } const numbers = [1, 2, 3]; console.log(multiple(...numbers)); // 6
The rest parameter allows us to pass an indefinite number of parameters to a function and access them in an array.
-
Let's look at one example below,
function multiple(a, b) { return a * b; } console.log(multiple(1, 2, 3, 4, 5)); // 2 ( 1 * 2)
- No, the function won't throw any error because to extra arguements but at the same time it won't even multiple them.
- The rest of the parameters can be included in the function definition by using three dots
...
followed by the name of the array that will contain them. The dots literally mean “gather the remaining parameters into an array”.
-
Now, Let's make this function using rest parameters
function multipleAll(...array) { let sum = 1; for (let num of array) { sum = sum * num; } return sum; } console.log(multipleAll(1)); // 1 console.log(multipleAll(10, 9)); // 90 console.log(multipleAll(10, 9, 8)); // 720
Remember: The rest parameters must be at the end. The rest parameters gather all remaining arguments, so it will causes an error. The
...rest
must always be last.
JSON
- JSON stands for JavaScript Object Notation. JSON is a way of storing and sharing data (usually between the browser and a server).
- It is a text-based format for representing structured data based on JavaScript object syntax. It basically has key-value pairs. But JSON names require double quotes.
-
Example:
var person = { "firstName" : "Prerana", "lastName" : "Nawar", "rollno" : "09" };
-
Features of JSON:
- It is light-weight
- Text based, human readable data exchange format
- It is language independent
- Easy to read and write
- Scalable
-
JSON.parse()
is used for parsing data that was received as JSON basically it converts a JSON string into a JavaScript object.- Example:
const json = '{"student":true, "rollno":9,"name":"Prerana"}'; const obj = JSON.parse(json); console.log(obj) console.log(obj.student); console.log(obj.rollno); > Object { student: true, rollno: 9, name: "Prerana" } > true > 9
-
JSON.stringify()
on the other hand is used to create JSON string out of the object or array it converts the javascript Object into the JSON string.
console.log(JSON.stringify({ num1: 1, num2: 2, num2: 3 })); // "{"num1":1, "num2":2, "num3":3 }"
So that's all these are my key Learning from the Chapter 4 of Book Eloquent Javascript. Also, Please do share your key learning from the Chapter 3 and what did you understood the most.
This is a Bloging Challenge from #teamtanayejschallenge
Here's a link to the Website: https://ejs-challenge.netlify.app/
References:
Thank you very much for the patience. I’d love to hear your feedback about the post. Let me know what you think about this article, and javascript in general, through my Twitter and LinkedIn handles. I would love to connect with you out there!
Peace!
Top comments (1)
nice