An Encounter with JavaScript Objects

Video Statistics and Information

Video
Captions Word Cloud
Reddit Comments
Captions
[Music] you unlock this door with the key of imagination this is an object a collection of properties where each property associate say key to a value earlier in the course we learned that there are seven primitive data types in Java Script primitives represent a single value like a number or a string and anything that's not a primitive is an object in other words everything interesting that happens in JavaScript is made possible by the object datatype today we'll take a deep dive into how the JavaScript object works and look at modern syntax and methods we can use to make our code cleaner and more efficient if you're new here like and subscribe and grab all of the videos on this free JavaScript course from bioship io an object is conceptually similar to a dictionary or a map that you might find in other programming languages the most straightforward way to create an object is to use the literal syntax simply define a variable equal to curly braces inside the braces you define properties separated by commas a property is essentially a key value pair where the left side is the property name and the right side is the property value the property name needs to be a unique value that can be coerced to a string the value can be anything you want a primitive another object a function or whatever now even though we define this object as a const variable we can still set properties on it after it's been created we can use bracket notation on the object followed by the name of the property equal to whatever value we want to set there then later in the code we can read or get that property using the same bracket notation now let's imagine that we've walked into an alternate universe because in JavaScript there is always more than one way to do things this time we'll create a new object using the constructor syntax then we'll set properties on it using dot notation dot notation looks a lot cleaner but your property names will need to be a continuous string that does not start with a number if you have property names with spaces or that start with numbers you'll get a syntax error if you try to call them with dot notation but now we've fallen into yet another alternate universe this time we'll use a static method on the object class called create you wouldn't normally use this one for an empty object it's most useful when you have an existing object and you want it to inherit its properties or in other words use the existing object as a prototype and this is one of the weirder parts of JavaScript so let's look at it a little more closely first we have a plain JavaScript object called organism it contains a DNA property of a random number and we create a new object with object create passing the organism as the prototype when we console.log the new object you'll notice that it's still a blank object but if we call the DNA property on this object we get a result back so it's almost like an invisible property on the new object that's because it exists on this objects prototype and we can see this property actually lives on the prototype by calling object get prototype of which returns the original object we created [Music] [Music] we're going to add a property to the object by using object defined property it takes the object as its first argument the name of the key as the second argument then an object with some options on it known as a descriptor as the third argument we can use the value option in the descriptor to create an object that is identical to the ones in the previous examples however we can now do more advanced things here as well like to find a getter and that would access the property by calling a function now most casual users of JavaScript won't need to use defined property on a regular basis but it is important to know how it works if you really want to understand the language in most cases you'll likely be working with the literal syntax and it does have a few cool tricks up its sleeve let's say we have a couple of variables and we want to set those variables on an object with the same property names as the variable in the olden days we would have to duplicate the property name with the variable but in modern times we can simply add the variable to the object literal and it will coerce the variable name to the property name and we can do a similar thing in Reverse with destructuring this time we want to read an object's properties and set them as variables to use in our local code in the olden days we would have to declare a variable and then set its value equal to the object property nowadays we can define multiple variables with a single line of code and JavaScript will match the variable names to the property names on the object but what if you want to use this awesome syntax but give your variable a different name sometimes you might have to do this to avoid a name collision with an existing variable just add a colon after the property name and then you can name your D structured variable whatever you want now what if your to try to take this code and then add another property with the same name this code won't throw an error instead it will overwrite the value on the left with the value on the right this is important to know because sometimes you might compute properties that you don't know until run time like you might want to create an object based on some data you fetch from a database you can compute property names by wrapping them in brackets and then place an expression inside and it will compute that value when the object is created in this example we have a function that generates a random number we can then call that function inside of the brackets to generate the key for this object when the object is created and you'll notice every time we refresh we get a different key or a name for this property now object properties can also take functions as their value and when a function lives on an object it's called a method you can define a method using the shorthand syntax where you omit the property name and just define a named function directly in the object literal and we can also use get and set keywords here to define getters and setters on this object when you define a method on an object this refers to this object however if you remember from the last video if you use the arrow function syntax here it will refer to the global this context for example if we convert our make web method into an arrow function this dot web will refer to the global web value as opposed to the internal property on this object so that's just a weird little thing to get used to in JavaScript an interesting thing you can do with the this keyword is chain methods together you'll see the syntax used in different JavaScript libraries with the most famous example being jQuery so the question is how do we chained together methods while keeping a reference to the same object I kind of already gave you the answer because remember I said the this keyword refers to the parent object when defined in name so if you want to chain method calls together all you have to do is return this from the method now any method you call will return the reference to the original object and that provides a good segue into the topic of object references previously in the course we learned the difference between the call stack and the heap primitive values are short-lived in most cases in the call stack while javascript objects are kept as references in the heap let's take a second to look at the implications of this because it's very important let's look at how things work first with primitives we'll initialize a variable a and then set B equal to a as you would expect they're both the same value but they're actually both pointing to their own primitive value so that means if we change a to a different value console.log them again you can see a has the new value but B still has the original value that it got from a now let's go ahead and refactor things to make a and object the big difference here is that B is making a reference to the object created in a they are both referencing the same object kept in the heap memory as opposed to copying the value like it did with a primitive after we update the property you can see that they both console.log the same object because again they're both sharing the same reference to it now that you know how it references work let's take a look at how we can combine objects together if you're updating the same object in multiple places it can be kind of difficult because of the weight references work in many cases you simply want to clone that object's property into a new object and one way to achieve that is with object to sign let's see how it can change the behavior of our previous example instead of setting B equal to a we use object to sign to take a brand new object and assign A's properties to it now it's important to keep in mind that this only uses the internal and numerable properties of a you can see exactly which properties will be copied over by using object get own property names and that will give you an array of all the property names owned directly by this object that means any other properties that had inherited higher up in the prototype chain would not be copied over in addition if this object were to reference other objects in its properties those objects would not be recursively deep copied over as well that means if a was making a reference to other objects those objects would still be copied over by reference it wouldn't recursively copy all the values in those nested objects I'm not sure at all if you're looking to clone objects like this a better alternative might be to use these spread syntax there are some very minor differences between the two but they can be used interchangeably in most cases and the spread syntax just looks a lot nicer when you're combining a lot of objects together now at the very beginning of the video I defined an object as a collection of key-value pairs and when you have a collection of something you likely want to loop over it looping over an array is easy but how do we loop over an object well one option is to use a four in loop this will loop over all of the enumerable properties in the object as well as its prototypes and this can be very very confusing so most people tend to avoid the for in loop a better alternative is to get the keys or values as an array you can use object keys or values to do exactly that then you can loop over them with a regular for loop or you can use one of the built-in array methods like for each but what if you want to loop over both the keys and the values together you can get an array of tuples using object entries and you can D structure that key and value variables in the loop now I showed you earlier how to create a new object using the new keyword but what if you want to customize the way that object is created you can do that easily in JavaScript by writing a constructor function by convention you should always capitalize the name of this function in this case we have a zombie function and it takes an argument of name we'll take that argument and define it as an internal property on the object and then we can handle additional setup in this function like setting a timestamp and also defining some methods you'll notice that it's the this keyword that allows us to reference internal properties on this object when it's created or instantiated so this function is actually very similar to a class like you might find in other object-oriented programming languages when you define a constructor function like this the way you initialize a new object is to put the new keyword in front of it now in modern JavaScript we could actually skip the function and just use the class keyword but the important takeaway here is that we're using a function to instantiate or create a new object the class keyword is mostly just syntactic sugar for this process as you can see javascript objects are very flexible and a core building block up a language I'm going to go ahead and wrap things up there if this video helped you please like and subscribe and make sure to check out the full JavaScript Khorasan buyer ship IO thanks for watching and I will talk to you soon beauty is in the eye of beholder [Music]
Info
Channel: Fireship
Views: 73,974
Rating: undefined out of 5
Keywords: webdev, lesson, tutorial, node.js, js tutorial, js objects, javascript objects, javascript, oop, object oriented programming, js functions, js full course, js course, js beginners, javascript course, es6, ecmascript, js spread, js destructuring
Id: napDjGFjHR0
Channel Id: undefined
Length: 10min 37sec (637 seconds)
Published: Fri Oct 18 2019
Related Videos
Note
Please note that this website is currently a work in progress! Lots of interesting data and statistics to come.