Skip to content

Instantly share code, notes, and snippets.

@FunctionDJ
Created February 7, 2020 18:09
Show Gist options
  • Save FunctionDJ/5f080f3b9c22e1f781c88a2e4f8aea9f to your computer and use it in GitHub Desktop.
Save FunctionDJ/5f080f3b9c22e1f781c88a2e4f8aea9f to your computer and use it in GitHub Desktop.
How the swap function works
// We're given this function
x = (y=>y)(y,y=x)
// It assignes something to x
// y => y is an arrow function with implicit return
// implicit return means that the "function body" is just an expression that we return
// We can write y => y like this
y => {
return y;
}
// So we can turn our arrow function to a classic named function like this:
function foo(y) {
return y;
}
// It's wrapped in parantheses so it's a function expression, essentially a function as a value that we could assign to a variable for example.
// We can write our function expression like this
(function(y) {
return y;
});
// Here this function is being called with the second set of parentheses (y, y = x)
// We can write is like this
(function(y) {
return y;
})(y, y = x);
// Which is basically the same as defining our function the classic way first
function foo(y) {
return y;
}
foo(y, y = x); // Looks more familiar?
// So what's the second parameter y = x doing? Our function is just using one parameter.
// Turns out functions in JavaScript don't care if they are passed more parameters than they use.
// Parameters are always expressions (something that expresses a value), but they can always contain assignments like y = x
// In words, it's "the second parameter is the value of y, which has the value of x"
// => This is NOT the same as passing x because now our y variable has the value of x!
// Another important aspect is that primitives (most things that aren't objects [objects include functions and arrays]) are always passed to functions by cloning them
// => So when we pass (y, y = x) JavaScript will copy the value of y for the function to process and then assign the value of x to OUR outside y
// Take a look at this example:
let x = 1;
let y = 2;
function foo(y) {
// the value passed was copied because it's a primitive, therefore it's 2
console.log(y); // 2
return y;
}
foo(y, y = x);
console.log(y); // 1
// y is 1 out here because we ran y = x
// So in the above example x is still = 1, unless...
let x = 1;
let y = 2;
function foo(y) {
return y; // return 2
}
x = foo(y, y = x); // x is now = 2!
// Since we know our foo function returns our "old" value of y, and that y now holds the value of our "old" x, we know we have swapped the two variables!
// Let's collapse this code
let x = 1;
let y = 2;
x = (function(y) {
return y;
})(y, y = x);
// And now turn the function into an arrow function
let x = 1;
let y = 2;
x = (y => {return y})(y, y = x);
// Implicit return, remove whitespaces just for confusion
x=(y=>y)(y,y=x)
// 🎉
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment