Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Does a JavaScript variable not declared with var become global?

I have the following code in one file:

function refreshGridSuccess(responseText, entity) {

    oTable = $('#dataTable').dataTable({
        "sScrollX": "100%",

In another file I have:

$('#detailData')
        .on('click', '.sort-up', function (event) {
            event.preventDefault();
            var column = $(this).closest('th'),
                columnIndex = column.parent().children().index(column.get(0));
            oTable.fnSort([[columnIndex, 'asc']]);
            return false;
        })

I have no definition for oTable except here. The scripts seem to work so does that mean that oTable was somehow made into a global variable?

Now I am trying to start using Typescript and it will not accept Otable without it being declared. Is there a way I can declare oTable as an object or do I have to declare it as an object to be the same type as is returned by $('#dataTable').dataTable({}) ?

like image 688
Samantha J T Star Avatar asked Nov 11 '12 07:11

Samantha J T Star


2 Answers

If you're in the global scope then there's no difference. If you're in a function then "var" will create a local variable, "no var" will look up the scope chain until it finds the variable or hits the global scope (at which point it will create it).

Found here: What is the purpose of the var keyword and when to use it (or omit it)?

like image 149
Yatrix Avatar answered Oct 08 '22 14:10

Yatrix


Yes, a variable not declared with var becomes global. When used outside of a function's scope it is not necessarily required, however, using a globally defined variable which was defined in a function results in unpredictable results.

"Failure to declare the variable in these cases will very likely lead to unexpected results. For that reason, in ECMAScript 5 strict mode, assigning a value an undeclared variable inside a function throws an error." - https://developer.mozilla.org/en-US/docs/JavaScript/Reference/Statements/var

like image 42
Travis J Avatar answered Oct 08 '22 14:10

Travis J