2
addToBasket = (id, qty) ->
    if $.cookie('basket')?
        # Basket exists
        basket = $.parseJSON($.cookie('basket'))
        basket.push( { 'id': id, 'qty': qty } )
        $.cookie('basket', JSON.stringify(basket))
    else
        # Basket doesn't exist
        alert 'Creating basket'
        basket = JSON.parse([{'id': id, 'qty': qty}])
        $.cookie('basket', JSON.stringify(basket))

I'm tearing my hair out; I cannot get the (compiled equivalent) function to run, always getting the illegal token error. I've checked for rogue, invisible characters and there's nothing besides CR/LFs in there.

user1381745
  • 3,850
  • 2
  • 21
  • 35
  • You sure that the question mark on line 2 of your sample is correct? I'm not a coffeescript professional, but cannot find anything regarding question marks in the docs: http://coffeescript.org/#conditionals – Spontifixus Feb 06 '13 at 17:53
  • @Spontifixus Yeah, it's listed as "The Existential Operator" on that page. I tried the bog standard "isnt undefined" initially with no difference; the ? was just a tidying up. – user1381745 Feb 06 '13 at 17:56
  • Ah well... The rest of your code looks fine enough. You do parse the `$.cookie('basket')` though. Could there be anything in the "basket" the JSON parser chokes on? – Spontifixus Feb 06 '13 at 17:59

1 Answers1

1

You're calling JSON.parse on an array, which apparently qualifies as a syntax error instead of a normal exception due to the way browsers implement it. You're essentially doing this:

JSON.parse([{id: 123}].toString())

Which is the same as:

JSON.parse('[object Object]')

Which is illegal JSON, hence the error.

Ian Henry
  • 22,255
  • 4
  • 50
  • 61