1

The following JavaScript works correctly in all browsers except IE 7 and 8:

if (typeof django != 'undefined') {
    console.log('Django admin loaded');
    var jQuery = django.jQuery;
}

This code is on top of a JavaScript file that is loaded both inside Django's admin interface and on our public pages. Django's admin loads its own jQuery, so we use that one preferably ...

However, IE 7 and 8 executes the variable assignment inside this if statement even if the condition (typeof django != 'undefined') is false. At the same time, the console.log() is not executed :-/ Removing the var keyword, the same code works perfectly also in IE 7 and 8:

if (typeof django != 'undefined') {
    console.log('Django admin loaded');
    jQuery = django.jQuery;
}

But why? That doesn't make any sense, does it?

Liam
  • 27,717
  • 28
  • 128
  • 190
Simon Steinberger
  • 6,605
  • 5
  • 55
  • 97

3 Answers3

5

ALL browsers will do this. It's called hoisting.

function test() {
    if( false) {
        var abc;
    }
    alert(abc); // expect ReferenceError, get undefined
}

Since you're defining jQuery, you probably want that as a global variable, so window.jQuery = django.jQuery should do just fine.

Niet the Dark Absol
  • 320,036
  • 81
  • 464
  • 592
1

There is no such thing as block scope within javascript (please see here for more details of JS scoping: What is the scope of variables in JavaScript?).

Your initial code doesn't make much sense anyway - if you are trying to set the global jQuery variable, then your code should be:

if (typeof django != 'undefined') {
    console.log('Django admin loaded');
    jQuery = django.jQuery;
}

What you are seeing is probably a difference with how IE7 and 8 handle their JS scopes.

Community
  • 1
  • 1
Paddy
  • 33,309
  • 15
  • 79
  • 114
  • Possibly some further useful reading: http://www.adequatelygood.com/JavaScript-Scoping-and-Hoisting.html – Paddy Aug 12 '14 at 08:50
0

If you define the var keyword then you need to do like this:

if (typeof django != 'undefined') {
    console.log('Django admin loaded');
    var jQuery = django;
    django.jQuery; // or django = django.jQuery
}
Bhojendra Rauniyar
  • 83,432
  • 35
  • 168
  • 231