Understanding Objects in Javascript
Let us thus discuss Javascript object creation. Actually, they are rather like the language's bread and butter. Fundamentally, objects are simply flexible bundles of goodies, or properties, where each property is essentially a name (or key) connected to a value. The great thing is that we jazz it out if the value is a function by calling it a method. Sounds good, right?
Simply said, consider objects as groups of key-value pairs hanging about. Object literal syntax—that is, rolling with the new keyword together with a constructor function—allows you to create objects in Javascript. For precisely modeling real-world objects right in your code, they are quite convenient. Imagine designing a user in a system or a product for an online store; objects enable that. Learning to play with objects—such as adding, modifying, or eliminating properties—opens up all kinds of opportunities with Javascript.
Introduction to Properties in Javascript Objects
Now let's explore Javascript object properties. Consider properties as the little details or characteristics connected to a given name of an object. Every one bears a name and a value. These days, the name can be whatever string you want, even an empty one should you be daring! Regarding the value, except from undefined, it can be almost anything Javascript agrees with.
var car = {
make: 'Toyota',
model: 'Camry',
year: 2020
};
View that. In our tiny automobile example above, "make," "model," and "year" are the property names; these couple with values like "Toyota," "Camry," and 2020.
These days, two common methods to acquire these assets are:
1. Dot notation: Most programmers on the planet use dot notation as their preferred technique.
console.log(car.make); // Outputs: Toyota
2. Bracket notation: If your property name hangs out in a variable or if it's not quite the typical valid Javascript identifier, bracket notation is pretty helpful.
var property = 'model';
console.log(car[property]); // Outputs: Camry
Javascript objects let you add, change, or discard properties whenever you so want. This makes creating complex and dynamic data sets simple.
How to Access Properties in Javascript
Referring to the properties within Javascript objects? Quite simple, actually. As we discussed, there are two primary approaches to accomplish it: bracket notation and dot notation. Dot notation is now your friend when you know the name of the property you are seeking. It's the most often used approach as it's direct and easy.
var person = {
name: 'John',
age: 30
};
console.log(person.name); // Outputs: John
console.log(person.age); // Outputs: 30
Then there's bracket notation, which is quite helpful whether the property name hangs out in a variable or if it's something a little challenging, such as with spaces or special characters.
var property = 'name';
console.log(person[property]); // Outputs: John
var specialProperty = 'favorite color';
person[specialProperty] = 'blue';
console.log(person[specialProperty]); // Outputs: blue
A little heads up: Javascript will provide you undefined as its means of indicating "not found" should you try to access a property that isn't present.
console.log(person.height); // Outputs: undefined
Working with data kept in Javascript objects requires you to become at ease with property access. One of those basic abilities that simplifies life while handling code is knowledge of codes.
Why and When to Delete Properties in Javascript
Now let's discuss why you would wish to ignore certain of the properties of a Javascript object. You could be doing this for a few different things. Memory management is clearly one major factor. By clearing some memory, eliminating a property you have lingering around that you no longer need will make your application operate somewhat lighter.
Stopping properties from returning covertly into your code later is another wise action for deletion. Eliminating a property that passed its sell-by date can assist you prevent future problems or misinterpretation. Deleting properties also comes in helpful while you're reworking an object. Like, if you want a version of anything you have for a user with just the basics.
var user = {
name: 'John',
age: 30,
password: 'secret'
};
// Create a new object that only includes the name and age properties
var publicUser = Object.assign({}, user);
delete publicUser.password;
console.log(publicUser); // Outputs: { name: 'John', age: 30 }
In this case, we eliminated the password attribute from publicUser such that it wouldn't show up. Remember, the delete operator merely kicks the property out of the object itself. Should the attribute be inherited from the prototype, it will still be subtly visible in the backdrop.
Methods for Deleting Properties in Javascript
The reliable delete operator is your go-to tool for removing properties in Javascript. Like it was never ever there, this simple operator will totally eliminate a property from an object. Let's see this in action:
var person = {
name: 'John',
age: 30
};
delete person.age;
console.log(person); // Outputs: { name: 'John' }
See how the delete operator causes the age property to become non-personally identifiable? Just keep in mind that this just influences the item you are working with; it does not alter everything linked through the prototype chain.
Now some people might simply mark a property as unknown rather than totally removing it. Remember, though, this simply removes the related value; it does not really destroy the property.
person.age = undefined;
console.log(person); // Outputs: { name: 'John', age: undefined }
Here the age property is still hanging around but without value. Though most of the time you would be better off keeping with the delete operator to completely remove out properties, you could find usage for this.
Using the delete Operator in Javascript
In Javascript, the delete operator is like a handy magic eraser for your objects—handy for rendering properties vanished. All you have to do is point it at the object and the particular quality you want eliminated.
var student = {
name: 'John',
age: 20,
grade: 'A'
};
delete student.grade;
console.log(student); // Outputs: { name: 'John', age: 20 }
Here we have used our reliable delete operator to eliminate the grade property from the student object. Here's something interesting, though: the remove operator tells us whether we succeeded by either returning true or false (like to if you try deleting a non-configurable attribute).
console.log(delete student.grade); // Outputs: true
console.log(delete student.age); // Outputs: true
console.log(delete student.name); // Outputs: true
A brief note: albeit not from memory, the delete operator takes the property off of the object. When references to that property are absent, memory opens up. Furthermore, deleting just influences the object's own attributes; it has no effect on any property in the prototype chain. Therefore, the object can still access a property that you discard from a prototype by means of the prototype chain.
Understanding the Outcome of Deleting Properties
A property removed from a Javascript object using the delete operator leaves the object permanently changed. Try getting in touch once more; all you will get is vague.
var person = {
name: 'John',
age: 30
};
delete person.age;
console.log(person.age); // Outputs: undefined
Once we've dropped the age property from person, looking for person in this arrangement. Age lends you the cold shoulder with an unknown. The delete operator is clean in that it produces a true or false indication of whether the operation was successful; false is rare and typically denotes either the property wasn't present to start with or couldn't be eliminated.
console.log(delete person.age); // Outputs: true
console.log(delete person.height); // Outputs: true, even though the property does not exist
The surprise is that lopping off a piece of land has no effect on the prototype chain. Still within reach is any property bearing the same name higher down the chain.
var person = {
name: 'John',
age: 30
};
var employee = Object.create(person);
employee.job = 'Engineer';
delete employee.name;
console.log(employee.name); // Outputs: 'John', the name property from the person object
In the case above, even after we zap the name field from employee, its prototype—the person object—offers up its own name property to keep things operating smoothly.
Common Mistakes When Deleting Properties in Javascript
Let's discuss several error events developers could run across while attempting Javascript property deletion.
1.Trying to delete a property that does not exist: The delete operator won't cause a hersy fit should you attempt to remove a property that does not exist. Simply gently returns true. If you weren't anticipating this, this can be a little perplexing.
var person = {
name: 'John',
age: 30
};
console.log(delete person.height); // Outputs: true, even though the property does not exist
2. Trying to delete a non-configurable property: Some properties are indicated as non-configurable, which indicates they are here to stay rather than able to be deleted. Should you try to delete one, the delete operator will provide bogus results.
var obj = Object.defineProperty({}, 'property', {configurable: false});
console.log(delete obj.property); // Outputs: false
3.Setting a property to undefined instead of deleting it: While assignment undefined can feel like a delete, the property doesn't really vanish, which could cause shocks later on if set to unknown instead of deleted.
person.age = undefined;
console.log(person.age); // Outputs: undefined
console.log('age' in person); // Outputs: true
Here, albeit its value is unknown, the age attribute still persists on the person object.
4. Not knowing prototype chain behavior: A property that you remove will still be accessible if it shows up somewhere up the prototype chain.
var person = {
name: 'John',
age: 30
};
var employee = Object.create(person);
employee.name = 'Jane';
delete employee.name;
console.log(employee.name); // Outputs: 'John', the name property from the person object
In this scenario, the name from the prototype, person, is still ready to come up even though the name attribute on the employee object has disappeared.
Practical Examples of Deleting Properties in Javascript
Let us explore some real-life situations whereby you might wish to cut off properties from an item. Imagine you have an object representing a user in a system and you must send over a network request a slim version—just the basics.
var user = {
id: 1,
name: 'John',
email: 'john@example.com',
password: 'secret'
};
// Create a new object that only includes the id, name, and email properties
var publicUser = Object.assign({}, user);
delete publicUser.password;
console.log(publicUser); // Outputs: { id: 1, name: 'John', email: 'john@example.com' }
In this instance, we replace the password property from publicUser with one that is kept safe from prying eyes by use of network transfer. Removing attributes depending on specific criteria is another daily use-case. Perhaps you wish to sell any houses with null or unknown values.
var data = {
name: 'John',
age: null,
email: 'john@example.com',
address: undefined
};
for (var property in data) {
if (data[property] === null || data[property] === undefined) {
delete data[property];
}
}
console.log(data); // Outputs: { name: 'John', email: 'john@example.com' }
Here, by rapidly traversing every property in the data object, a for-in loop proves useful. Out it goes any property with a null or undefined value!
Best Practices for Deleting Properties in Javascript
Here are some pointers and ideas to help you smoothly and hassle-free delete attributes in Javascript:
1. Use the delete operator: Your first tool for kicking a property out of an object is the delete operator. It not only cleans but also aids with memory management by totally removing the property.
var person = {
name: 'John',
age: 30
};
delete person.age;
console.log(person); // Outputs: { name: 'John' }
2. Verify whether the property exists before you go and destroy it: It's wise to do this twice-check as well. In this sense, you keep clear of any unanticipated shocks and prevent needless effort.
if ('age' in person) {
delete person.age;
}
3. Know prototype chain behavior: Deleting the same property name from the main object won't significantly affect anything if the same property name is floating up in the prototype chain. It is still available. Remember this to steer clear of any uncertainty ahead.
var person = {
name: 'John',
age: 30
};
var employee = Object.create(person);
employee.name = 'Jane';
delete employee.name;
console.log(employee.name); // Outputs: 'John', the name property from the person object
4. Avoid deleting properties in a loop: Using the delete operator repeatedly in a loop can slow things down. If you’re looking to shed multiple properties, think about crafting a fresh object with only what’s necessary instead.
var user = {
id: 1,
name: 'John',
email: 'john@example.com',
password: 'secret'
};
// Create a new object that only includes the id, name, and email properties
var publicUser = Object.assign({}, user);
delete publicUser.password;
console.log(publicUser); // Outputs: { id: 1, name: 'John', email: 'john@example.com' }