+ 7
Is this the magic of the javascript "spread operator"?
I was playing with some fancy javascript methods and newly added features. So out of curiosity, I used the spread operator with a string but the result I got was miraculous enough : const string = 'MAGIC'; console.log(...string); // => M A G I C document.write(...string); // output is the same as the string => MAGIC const case1 = [...string]; const case2 = [...string]; console.log(case1 == case2); // compare value => false console.log(case1 === case2); // compare type => false What the heck is happening? 😶 Seeme like it is violating the maximum rules of javascript! Code Demo : https://code.sololearn.com/WIsPYHj5EEqk/?ref=app
18 Respuestas
+ 9
const string = 'MAGIC'
console.log(...string) is equivalent to
console.log('M','A','G','I','C');
This is rest parameters, not spread operator.
edited: sorry, it's called spread syntax, not rest parameters
+ 8
To confuse you even further, do this:
const x = {...string};
console.log(JSON.stringify(x));
+ 6
Burey
const x = {...string};
console.log(JSON.stringify(x)); //{"0":"M","1":"A","2":"G","3":"I","4":"C"}
I think it makes a key-value pair of the string. 🤔
+ 6
Arrays in javascript are considered as objects
And objects cannot be compared...nor by its type.. nor by value
+ 4
case = [...string] create new copy of array.
The array of case1 is not same as case2, there are different copies, with same content.
+ 4
ChillPill - [meme mode] That was a really good correction! I figured it out :))
+ 3
"console.log(case1 == case2) isn't comparing values" - but what IS it comparing then? 😨
I feel so lost in nowadays programming, I come from old C/C++ and the things I thought I knew are not how I knew them anymore :(
+ 3
You may find answer in:-
1) https://www.geeksforgeeks.org/javascript-spread-operator/
2) https://stackabuse.com/spread-operator-in-javascript/
3) https://medium.com/coding-at-dawn/how-to-use-the-spread-operator-in-javascript-b9e4a8b06fab
4) https://medium.com/front-end-weekly/es6-magical-stuffs-spread-syntax-in-depth-afdd0118ebd0
+ 2
Correction
console.log(...string) is using spread syntax,
+ 2
🤯
+ 2
Mirielle[Inactive] until both arrays are sorted in same ways and contains values wich support Json stringification ;)
+ 1
What a discovery. The second one is false because arrays in JavaScript are objects. And obj compared always returns false.
+ 1
Calviղ & sajid chowdhury but what about the rest? 🤔
+ 1
Carlos Nazario This is a warning to your spamming behavior in posting irrelevant answer to Q&A questions.
Remove your spam immediately!
0
What's wrong with that code ? Everything is normal. When you do a spread in brackets you get an array which is an object that has its own reference and cannot be equal to any other array. The only thing bizarre is the output in console and the output in the dom difference.
0
There's a mistake in the code ChillPill - [meme mode]