Thursday, November 28, 2019

Use the delete keyword in JavaScript to remove a property from an object.

Beyond this goofy example here, you can actually do something with the delete keyword! At the TypeScript Playground I wrote this TypeScript:

var foo = {
   bar: 13,
   baz: "lucky",
   qux: true
}
console.log({ ...foo });
delete foo.baz;
console.log(foo);

 
 

...which got turned into this JavaScript...

"use strict";
var foo = {
   bar: 13,
   baz: "lucky",
   qux: true
};
console.log(Object.assign({}, foo));
delete foo.baz;
console.log(foo);

 
 

When you run this stuff two objects get logged to the console and you can clearly see the baz on the first object and not the second object. Yay!

No comments:

Post a Comment