I have some simple code as shown below. Unfortunately, it fails on the second destructuring assignment and I am unable to figure out why.
Code:
let prev, curr
[prev, curr] = setPreviousAndCurrent(1, prev, curr)
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
[prev, curr] = setPreviousAndCurrent(2, prev, curr) // fails on this assignment
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
[prev, curr] = setPreviousAndCurrent(3, prev, curr)
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
function setPreviousAndCurrent(data, previous, current) {
// We cannot use the ! operator for checking against values of previous and current since value can be 0, which will give a false positive
if (previous === undefined) {
previous = data
} else if (previous && current === undefined) {
current = data
} else {
previous = current
current = data
}
return [previous, current]
}
Output:
❯ node js_test.js
Previous: 1
Current undefined
/js_test.js:7
[prev, curr] = setPreviousAndCurrent(2, prev, curr)
^
TypeError: Cannot set property 'undefined' of undefined
at Object.<anonymous> (/js_test.js:7:14)
at Module._compile (internal/modules/cjs/loader.js:971:30)
at Object.Module._extensions..js (internal/modules/cjs/loader.js:1011:10)
at Module.load (internal/modules/cjs/loader.js:822:32)
at Function.Module._load (internal/modules/cjs/loader.js:730:14)
at Function.Module.runMain (internal/modules/cjs/loader.js:1051:12)
at internal/main/run_main_module.js:16:11
If I change the code to (as shown below), it works as expected.
Code:
let prev, curr
[prev, curr] = setPreviousAndCurrent(1, prev, curr)
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
let temp = setPreviousAndCurrent(2, prev, curr)
prev = temp[0]
curr = temp[1]
// [prev, curr] = setPreviousAndCurrent(2, prev, curr)
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
temp = setPreviousAndCurrent(3, prev, curr)
prev = temp[0]
curr = temp[1]
// [prev, curr] = setPreviousAndCurrent(3, prev, curr)
console.log(`Previous: ${prev}`)
console.log(`Current ${curr}\n`)
function setPreviousAndCurrent(data, previous, current) {
// We cannot use the ! operator for checking against values of previous and current since value can be 0, which will give a false positive
if (previous === undefined) {
previous = data
} else if (previous && current === undefined) {
current = data
} else {
previous = current
current = data
}
return [previous, current]
}
// Works as expected
Output:
❯ node js_test.js
Previous: 1
Current undefined
Previous: 1
Current 2
Previous: 2
Current 3
I am unable to figure out why this happens since it is clear that the function is running and returning the expected value but is unable to assign it via destructuring to the variables prev and curr, the second time it is called.
Appreciate the responses! Thank You! :)