tjfwalker
tjfwalker

Reputation: 494

Why won't this object method return a boolean value Javascript

My app's js file includes this bit here:

var drawer = document.getElementById('b_001');

drawer.isOpen = function() {
  this.classList.contains('open');
};

When I call it in the console, drawer.isOpen(), I expect a boolean value, true or false. However, undefined is returned instead. Why is this?

Upvotes: 0

Views: 61

Answers (2)

KooiInc
KooiInc

Reputation: 122986

You'll have to return it:

drawer.isOpen = function() {
  return this.classList.contains('open');
//^ here  
};

If a function doesn't return anything, the return value is considered undefined, as this snippet demonstrates:

var report = document.querySelector('#result');

report.innerHTML += doStuff(5);        // nothing returned
report.innerHTML += '<br>'+addFive(5); // a result is returned

function doStuff(val) {
  val = val || 0;
  val += 5;
}

function addFive(val) {
  val = val || 0;
  val += 5;
  return val;
}
<div id="result"></div>

Upvotes: 2

N.R
N.R

Reputation: 88

you need a return statement

 return this.classList.contains('open');

Upvotes: 3

Related Questions