6

I've been making a program and I want to know the difference between starting two functions like so:

$(function () {
   //content
});

and

function Name () {
    //content
}

Also, why can't I name the first example? I tried changing the first example to the second type, and the function stopped working fully. I've used jQuery with the first example and everything was fine, but with a different example, the function stopped working.

So what's the difference?

1
  • $ is a function. $(function() {...}); is invoking that function with another function as its argument. Just like function foobar() {...} $(foobar); Commented May 18, 2013 at 19:29

4 Answers 4

15

$(function () {}); this is shortcut for $(document).ready(function(){});

while this:

function Name () {
    //content
}

is standard javascript function.

Sign up to request clarification or add additional context in comments.

1 Comment

where and what is the name in case of jquery?
4

The first is a function expression that is used for the jQuery ready event, while the second is a function.

Using $(function(){...}); is shorthand for $(document).ready(function(){...});.

The ready event happens when the document has completed loading, so the event handler will run automatically. A regular function doesn't run at all unless you call it.

You can naturally use a regular function instead of the function expression for the event handler:

function readyHandler() {
  ...
}

$(readyHandler); // or $(document).ready(readyHandler);

A function expression can be named, for example:

var x = function y() { ... };

However, the name of the function expression (y in the example) is not global, it's only usable inside the function itself. Also, the exact implementation of this differs between browsers, so you should avoid using it.

Comments

1

The first one is a so-called anonymous function. It gets executed on the document ready event

$(document).ready(...);

and is jQuery convention. Since you cannot call it directly, it has no / needs no name.

The second version is a standard function that you can call by name at any time.

If you change the first one to the second notation, it will no longer run at document ready automaticly. Safe way is to move the "worklaod" into a function with the second notation, and create a line with the first notation that calls the funciton. That way you have the best of both worlds: a separately callable function, and simple auto-execution.

Comments

1

The first one:

 $(function () {
 //content
 });

is passing an anonymous function to the jQuery object $, equivalent to $(document).ready(function(){});

the second is just a JavaScript function named Name.

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.