4

I've tried both these:

if foo
  if foo[0] == bar.baz[0]
    input.form-control-success(type="text")
  else
    input.form-control-danger(type="text")
else
  input(type="text")
unless foo === undefined
  if foo[0] == bar.baz[0]
    input.form-control-success(type="text")
  else
    input.form-control-danger(type="text")
else
  input(type="text")

But in both cases I get the error

Cannot read property '0' of undefined

on the line if foo[0] == bar.baz[0].


The situation is that sometimes foo is passed to pug, and sometimes it isn't.

foo is an array when it is passed, and if it is passed I need to do something based on whether it's xth element is the same as another array's xth element.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119

2 Answers2

2

undefined is falsy in js...it looks like bar.baz may be your culprit.

theonlygusti
  • 11,032
  • 11
  • 64
  • 119
adamz4008
  • 660
  • 4
  • 10
  • Your initial assumption was correct. You can't inspect these variables in chrome though because they're compiled server-side – theonlygusti Dec 12 '17 at 11:20
2

You can use typeof to check if a variable is undefined. It always returns a string.

if (typeof foo === 'undefined') {
  console.log('foo is undefined');
}

var foo = ['one', 'two', 'three'];

if (typeof foo !== 'undefined') {
  // access elements
  console.log(foo[0] + ', ' + foo[1] + ', ' + foo[2]);
}
Crappy
  • 441
  • 3
  • 7