Skip to content

Instantly share code, notes, and snippets.

@elledienne
Last active May 13, 2019 15:21
Show Gist options
  • Save elledienne/a550370ea40e749c4f076c6f98ed8cc8 to your computer and use it in GitHub Desktop.
Save elledienne/a550370ea40e749c4f076c6f98ed8cc8 to your computer and use it in GitHub Desktop.
[INTERVIEW] Coding challenge to test scope, ES6, IIFE
// Remember to overwite the code in CodeShare, JSFiddle, etc. to restore the inital state of the test and to avoid
// showing to candidates the changes made during other interwies
// TASKS:
// 1. Ask to developer to analyze the provide (broken) snippet:
// - The dev should be able to understand the intent of the snipped
// - The dev should be able to predict the (unexpected) behaviour
// - The dev should be able to provide at least one fix (and discuss about it)
const initialValues = [0, 1, 2, 3, 4, 5, 6, 7, 8, 9];
const summedValues = [];
// BROKEN VERSION: Uses "var", not scoped
for (var i = 0; i < initialValues.length; i++) {
summedValues.push(() => {
console.log(initialValues[i]);
});
}
console.log(summedValues.forEach(v => v())) // 10x Undefined
// JUST REFERENCE, DELETE BEFORE INTERVIEWING
// CORRECT VERSION: Uses "let", at every iteration different instances of the variable i
for (let i = 0; i < initialValues.length; i++) {
summedValues.push(() => {
console.log(initialValues[i]);
});
}
console.log(summedValues.forEach(v => v())) // 0, 1, 2, 3, 4, ...
// JUST REFERENCE, DELETE BEFORE INTERVIEWING
// CORRECT VERSION: Uses IIFE, i is scoped inside the IIFE
for (let i = 0; i < initialValues.length; i++) {
summedValues.push((() => () => (console.log(initialValues[i])))());
}
console.log(summedValues.forEach(v => v())) // 0, 1, 2, 3, 4, ...
@elledienne
Copy link
Author

elledienne commented Jun 26, 2017

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment