How do I correctly clone a JavaScript object?

2022 update There’s a new JS standard called structured cloning. It works on all browsers: const clone = structuredClone(object); Old answer To do this for any object in JavaScript will not be simple or straightforward. You will run into the problem of erroneously picking up attributes from the object’s prototype that should be left in … Read more

Loop through an array in JavaScript

Three main options: for (var i = 0; i < xs.length; i++) { console.log(xs[i]); } xs.forEach((x, i) => console.log(x)); for (const x of xs) { console.log(x); } Detailed examples are below. 1. Sequential for loop: var myStringArray = [“Hello”,”World”]; var arrayLength = myStringArray.length; for (var i = 0; i < arrayLength; i++) { console.log(myStringArray[i]); //Do … Read more

How do I test for an empty JavaScript object?

ECMA 5+: // because Object.keys(new Date()).length === 0; // we have to do some additional check obj // 👈 null and undefined check && Object.keys(obj).length === 0 && Object.getPrototypeOf(obj) === Object.prototype Note, though, that this creates an unnecessary array (the return value of keys). Pre-ECMA 5: function isEmpty(obj) { for(var prop in obj) { if(Object.prototype.hasOwnProperty.call(obj, … Read more

tech