0
  • There is a code between the 1st log and the 2nd log. I assign the validate variable to the s variable using the let definition type.
console.log(validate); // 1. log

let s = validate;
if (s.location != null)
   delete s['location'];

console.log(validate.location); // 2. log

In this case, the screen output looks like this:

{ // 1
  min_price: 2,
  max_price: 5,
  location: { latitude: 234.2244555, longitude: 245.33333 }
}
undefined // 2

Isn't it very strange? Because after I do let s = validate; I do delete s['location]; but after this operation when I do console.log(validate.location); I get undefined.

  • So I wrote the following instead of let s = validate; on the code and the result was fine:
let s = {
  ...validate
};

In this case, when we take the screen output again, the output is fixed as follows:

{ // 1
  min_price: 2,
  max_price: 5,
  location: { latitude: 234.2244555, longitude: 245.33333 }
}
{ location: { latitude: 234.2244555, longitude: 245.33333 } } // 2

Now my question is, is the difference between let s = validate; and let s = { ...validate }; because of the let definition type? Because I couldn't find a logical explanation for this conflict.

  • 3
    Has nothing to do with `let`. When you do `s = validate` you're assigning a reference to `validate` to `s`. With the spread, you're making a shallow copy. – Heretic Monkey Jul 19 '23 at 12:24
  • 1
    *"Isn't it very strange?"* - Not at all. In that first example, both `s` and `validate` are references to the same object. Assigning an object reference to a new variable doesn't create a copy/clone of that object. – David Jul 19 '23 at 12:26

0 Answers0