Hoisting is where variable declarations are “hoisted” or lifted to the top of their scope. If the variable is inside a function, it is lifted to the top of the local/functional scope. If the variable is outside of a function, it is lifted to the top of the global scope. This is done regardless of where the variable declaration was made.
So, if we were to write the following in the global scope:
We would get back
undefined. The reason that we get back
undefined is that it is recognizing that the variable
hello exists, but because of hoisting, the variable declaration is hoisted to the top of the global scope, but the actual value given to the variable is not hoisted. The code is compiled as if it was written as:
Once the constructor function has been defined, then you can create instances like so:
You might be thinking, this is cool and all, but what does this have to do with prototypal inheritance? Hang on I’m getting there.
Now back to our example. Here we will add a method to calculate the age of the dogs (in dog years, of course), but we will add it outside of the constructor function using the prototype property.
By using the
prototype property, the objects
fefe, have access to the method
calculateAge. The reason that they have access to this method is because of prototypal inheritance (I told you that I would bring it all together). So if we were to run
fefe.calculateAge(), we would get the age of the dogs in dog years. Here is the full snippet of code:
Attributes are defined by the HTML (Hypertext Markup Language). They provide additional information about the HTML elements. Examples of attributes are:
Properties are defined by the DOM (Document Object Model). Once your browser parses your HTML elements, a DOM node is created. Because this node is an object, it has properties. Examples of properties are:
The main differences between attributes and properties are:
- Attributes are defined by HTML and properties are defined by the DOM.
- DOM properties are initialized by HTML attributes.
- Attribute values cannot be changed.
- Property values can change.
As you can see HTML attributes and DOM properties are two different things.
I hope that this article has helped you to better understand hoisting, prototypal inheritance, and the differences between HTML attributes and DOM properties. It is my even greater hope, that it will help you ace an interview and land you that frontend development job in which you are applying. I wish you the best of luck and thank you for taking the time to read this article.