Interview Question 3

by Arnaud Buchholz

HTML

<script src="https://arnaudbuchholz.github.io/blog/jsfiddle-assert.js"></script>
<h1>
Interview Question 3
</h1>
<blockquote>
  This code was developped in plain JavaScript <i>before</i> the <code>class</code> keyword was introduced and has a problem: 
  the length of <code>b</code> is not 1 even if only one item has been added to it.
  <ul>
    <li>Can you spot the issue ?</li>
  </ul>
  Feel free to express your thoughts openly and elaborate on your reasoning.
  You may propose changes to this code to test your reasoning.
</blockquote>

CSS

blockquote {
  padding: 0.5rem;
  margin: 1rem;
  background-color: lightgray;
}

JavaScript

function newList () {
  return {
    _items: [],
    add (item) {
      this._items.push(item)
    },
    get length () {
      return this._items.length
    }
    
  }
}

MyList.prototype = {
  _items: [],
  add (item) {
    this._items.push(item)
  },
  get length () {
    return this._items.length
  }
}

const a = new MyList()
a.add('A')
assert(() => a.length === 1)

const b = new MyList()
b.add('B')
assert(() => b.length === 1)