Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Javascript get value from array at index while avoiding undefined if index does not exist?

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?

like image 838
Zach Taylor Avatar asked Jul 13 '18 06:07

Zach Taylor


3 Answers

You could use in operator operator, which check if a property exists in an object/array with a conditional (ternary) operator ?: for either the value or some default value.

This approach saves falsy values as well.

const b = 0 in aa ? a[0] : <something other than undefined>;
like image 153
Nina Scholz Avatar answered Sep 21 '22 11:09

Nina Scholz


What you are seeing is basically a design decision. It's just how JavaScript works. For example PHP is similar in the sense that accessing a non existing index is a warning rather than a hard error. There's probably other language examples out there that behave this way.

To get around this:

A common way is indeed using b = a[0] || "default" however beware of the behaviour with falsy but not undefined values as for example:

var myarray = [ 0, null, "" ];

var a = myarray[0] || "default[0]";
var b = myarray[1] || "default[1]";
var c = myarray[2] || "default[2]";
var d = myarray[3] || "default[3]";

console.log(a, b, c, d);

If you want to strictly check for undefined while allowing falsy values to be used do be explicit:

    var myarray = [ 0, null, "" ];

    var a = myarray[0] !== undefined ? myarray[0] : "default[0]";
    var b = myarray[1] !== undefined ? myarray[1] : "default[1]";
    var c = myarray[2] !== undefined ? myarray[2] : "default[2]";
    var d = myarray[3] !== undefined ? myarray[3] : "default[3]";

    console.log(a, b, c, d);
like image 29
apokryfos Avatar answered Sep 21 '22 11:09

apokryfos


The JavaScript Execution is little different from other programming languages. JavaScript doesn't create intermediate code which languages like C, Java creates (eg- byte code). The first phase in Javascript is the declaration phase where variables are defined in their respective scope. The default scope is the global scope. Each function creates its own scope in javascript.

var a = 10;

So in 1st phase it will define 'a' in global scope. Note that its not initialising it with value 10. The next phase is the initialisation phase where the value of 10 is assigned to the var 'a'. if a is not declared any value it will be initialised as 'undefined'.

In the end you have to remember that its just the way JavaScript does it.

like image 23
Ashlesh Avatar answered Sep 19 '22 11:09

Ashlesh