Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Javascript, switching variables

Quick question about switching variables in Javascript. In python we can do the following:

test1, test2 = test2, test1

That will switch test1 for test2 and test 2 for test 1, in a single line of code. This approach dosent work in javascript tho, is there a similiar way to do it?

1 Answer

Steven Parker
Steven Parker
243,658 Points

Yes you can do this in JavaScript also, but the syntax is slightly different:

[test1, test2] = [test2, test1];

As you see, the terms are wrapped in array literals on both sides. This is known as "destructuring assignment".

Ty as always steven!

How long have you been programming, Steven? :-)

Steven Parker
Steven Parker
243,658 Points

About 8 for JavaScript. Around 35 in general.