Coming from Python, it is very odd for me to see this JavaScript:
a = []
b = a[0]
b === undefined // returns true
In Python a[0] would throw an index error, and would prevent you from continuing and potentially running into more errors in the future. B would never be set to undefined.
In Python I could do something like:
a = [1, 2, 3]
try:
b = a[5]
except IndexError:
print('Index out of range')
b could never be set to undefined, which would prevent potential weird things happening later on. What is the best way for me to handle this in JavaScript? I tend to want to try something like this:
a = []
b = a[0] || <something other than undefined>
In the case that a is supposed to be a list of objects it could be:
a = []
b = a[0] || {} // set b to empty object instead of undefined
I think a common way of handling this in JavaScript is handling it further down the line:
a = []
b = a[0]
if (b) {
// do something if b is defined
}
// or
if (!b) {
// do something if b is undefined
}
In JavaScript is there a best or common practice for avoiding setting something to undefined? And in this specific case of accessing an array what is the best way to avoid setting something to undefined?
const b = a[0] || <something other than undefined>is perfectly fine and is often done. IMO it's the preferable terse way, to avoid reassigningb. (unnecessary reassignment is often frowned upon)