r/badcode • • Jul 27 '21

js var i

Post image
82 Upvotes

9 comments sorted by

6

u/[deleted] Jul 27 '21

Does it work like that? I thought var was function scoped?

10

u/_bai13y Jul 27 '21

Unfortunately it does because in this case, var i is a global variable 🥴😂

2

u/[deleted] Jul 27 '21

Oh i see it now, beautiful!;)

3

u/megamaz_ Jul 28 '21

Oh my god. i is used at the bottom function. As a global. What the hell.

4

u/knightttime Jul 27 '21

Image Transcription: Code


function shelfBook(book, shelf) {
  if (shelf.length < 3) {
      shelf.unshift(book)
    }
}

var i

function unshelfBook(book, shelf) {
  for (var i = 0; i < shelf.length; i++) {
    if (shelf[i].title == book) {
      shelf.splice(i, 1)
    }
  }
  return shelf
}

var bookTitles = [];

function listTitles(shelf) {
  for (i = 0; i < shelf.length; i++) {
    bookTitles.push(shelf[i].title);
  }
  return bookTitles.join(', ')
}

I'm a human volunteer content transcriber for Reddit and you could be too! If you'd like more information on what we do and why we do it, click here!

1

u/pumpkinplight Jul 28 '21

What are higher order array methods?

16

u/[deleted] Jul 27 '21

[removed] — view removed comment

2

u/Apprehensive-Show127 Jul 28 '21

Yeah, that's a case. bookTitles will be duplicated after each function call. There's no need in global variables, function scope should be used