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
  • 21,956
  • 5
  • 41
  • 51
ZILONG PAN
  • 6,305
  • 1
  • 11
  • 6

2 Answers2

1

That is just jQuery short-hand for

$(document).ready(function() { ... });
varman
  • 8,704
  • 5
  • 19
  • 53
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
  • 16,156
  • 19
  • 74
  • 103