0
$(function () {
 console.log('hello');
 //...
})

I saw the code like this. Don't know the purpose of adding the first line (function)? Could Someone explain this?

Hassan Imam
  • 20,493
  • 5
  • 36
  • 47
ZILONG PAN
  • 4,117
  • 1
  • 9
  • 6

2 Answers2

1

That is just jQuery short-hand for

$(document).ready(function() { ... });
varman
  • 7,909
  • 4
  • 16
  • 48
1

Wrapping you Javascript code with $(function () {:

$(function () {
    console.log( "ready!" );
});

is the same (a Shorthand version) as writing:

$(document).ready(function() {
    console.log( "ready!" );
});

Which ensures the script will only run once the page Document Object Model (DOM) is ready for Javascript code to execute (Jquery docs).

Koby Douek
  • 15,427
  • 16
  • 64
  • 91