Issue #189 (delete operator, JS Utils, Sass, Text Editors)03/02/17
JavaScript's delete operator is a handy one to understand and be cautious about, so here's a quick summary of it along with some of its quirks.
The delete operator allows you to remove a property from an object. In the following code I'm removing the "one" property:
let myObj = { one: "one", two: true, three: 3 };
delete myObj.one;
console.log(myObj);
/* [object Object] { three: 3, two: true } */
|
View on JS Bin
The
delete operator has a return value, a Boolean representing whether the property was removed. So, from the previous code, if I logged the
delete line, it would return "true".
Another quirk is the fact that
delete will return
true even if you try to remove a non-existent property. I guess this is kind of like it's saying "item is not there" even if the action wasn't performed at that moment.
let myObj = {
one: "one",
two: true,
three: 3
};
console.log(delete myObj.four); // still logs true
|
View on JS Bin
Technically, variables and functions defined with
var,
let, and
const are properties of the global
window object (assuming JavaScript in the browser). However, using
delete on these is not allowed. In non-strict mode, such an operation will return
false and the item won't be deleted. In strict mode, you'll get a syntax error. This happens because these properties are considered non-configurable.
The last point I'll mention here is demonstrated in the next code example, when using
delete with arrays:
let myArrayOne = ['one', 'two', 'three', 'four'],
myArrayTwo = ['one', 'two', 'three', 'four'];
// remove Array element from each array
// using 2 different techniques
myArrayOne[2] = undefined;
delete myArrayTwo[2];
// same result, both have item as undefined
console.log(myArrayOne, myArrayTwo);
// length = 4 for both
console.log(
myArrayOne.length,
myArrayTwo.length
);
// But the item doesn't exist in one array
console.log(2 in myArrayOne); // true
console.log(2 in myArrayTwo); // false
|
View on JS Bin
As you can see, although the
delete operator can be used to remove an item from an array, the result is slightly different from setting an array item to
undefined. There's lots more info on delete
in MDN's article.
Now on to this week's tools!