Pumpinglemma
Pumpinglemma

Reputation: 113

Javascript code execution order strangeness

I have a section of Javascript/Coffeescript that seems to be executing out of order.

console.log list
console.log list[card_number]
if list[card_number]
  console.log "MATCHES"
  new_card = list[card_number]
else
  console.log "NO MATCHES"
  new_card = create_new_card(card_number)

create_new_card: (card_number) ->
  new_card =
    card_number: card_number
  list[new_card.card_number] = new_card
  return new_card

Every time I run this, the first console.log shows a list of cards that includes the new_card, Even if the card hasn't been created yet. Then it ALWAYS hits the else, no matter how many times it is run.

If I attempt to run list[<card_number>] in the Javascript console after this code runs, I receive the proper object, but each time the code runs on it's own, the same event happens.

Upvotes: 4

Views: 1052

Answers (3)

caleb
caleb

Reputation: 1637

Are you using Chrome? console.log does not execute immediately. Its a shame, but too bad for us.

Upvotes: 1

Esailija
Esailija

Reputation: 140210

In google chrome, if you want to log objects with the state they had at the time of logging, you need to log a clone object or just stringify it.

var a = [];
console.log(a);
a[0] = 3;

Will log [3] because it logs a live object, while this will log []:

var a = [];
console.log(JSON.parse(JSON.stringify(a)));
a[0] = 3;

It is also a live object logging but it is a throwaway clone that was cloned at the point in time when a didn't have any items.

This is not related to the possible logical errors in your code that @CallumRogers pointed out.

Upvotes: 5

Callum Rogers
Callum Rogers

Reputation: 15819

Your create_new_card function is wrong - you call new_card.number instead of new_card.card_number which always results in undefined being added to the list resulting the behaviour that you have observed. The correct version is:

create_new_card: (card_number) ->
  new_card =
    card_number: card_number
  list[new_card.card_number] = new_card
  return new_card

Upvotes: 1

Related Questions