What is the different between (function(){})(); to $(document).ready(function ()) [duplicate] - javascript

This question already has answers here:
jQuery $(function() {}) vs (function () {})($) [duplicate]
(3 answers)
Closed 3 years ago.
What is the difference between (function(){})(); and $(document).ready(function ())
First: (function(){})();
Second: $(document).ready(function ())
I have a question about it.
if I use it in the first option, there is an error when I click it. The Error is that it does not work and there is no error.
but if I use the second one, there is no error. It is not working.
what is the difference between to two ?

This will execute immediatly:
(function(){
console.log("Called immediately invoked function expression");
})();
Where as, the function passed to jQueries $.ready() function will execute when the document can be safely manipulated:
$(document).ready(function () {
console.log("The document is safe to be interacted with");
});
The reason the first method causes errors is likely because the HTML document is not ready for interaction at the time that your function is called (ie immednaitly).
The second approach will however ensure that (in most cases), any scripts, HTML, or other resources (which the JavaScript defined in that function might depend on) are loaded and present before that function is invoked.

Related

JQuery Syntax Similarity and Difference [duplicate]

This question already has answers here:
jQuery best practices in case of $('document').ready
(9 answers)
Closed 4 years ago.
Does this:
$(document).ready(function(){
alert("Hello World");
});
And this:
(function($){
alert("Hello World");
})(jQuery);
do the same thing?
The former is what I commonly use and the second I have seen used in several plugins. Are they the same, if not then what are their differences and which one to use when?
They are not the same.
The former is a document.ready event handler. It will run as soon as the DOMContentLoaded event fires. It can also be written like this:
$(function() {
alert("Hello World");
});
The latter is an Immediately Invoked Function Expression (IIFE). This will be executed immediately (as the name implies). Therefore you need to manually ensure that the DOM is in a state ready to be interacted with before you execute this logic. You can generally do this by placing the script at the end of the body tag, or within it's own document.ready handler. The latter is a little redundant when working with jQuery, though.

JavaScript setInterval callback before defining function? [duplicate]

This question already has answers here:
Why can I use a function before it's defined in JavaScript?
(7 answers)
Closed 5 years ago.
I'm currently a teacher's assistant in a web development course. Today, a student asked for help with his homework, in which he'd used setInterval, passing as the first parameter a function which he didn't define until a few lines of code later. I told him that wouldn't work, as the function would be undefined by the time the interval setting code was reached.
To my surprise, it worked perfectly. I've been trying to research this and am coming up blank: does JavaScript actually wait until the first execution of the callback to even see if the function name passed to it exists? That seems so counter-intuitive, but I can't imagine any other reason it would have worked. Where can I find out more about this unexpected behavior?
It depends:
If its a function expression :
//callback not defined ( exists but undefined)
var callback=function(){};
//callback defined
If its a function declaration :
//callback is defined
function callback(){}
//callback is defined
This is called hoisting, so vars and functions are moved to the top.
It also depends on the passed function too:
setInterval(callback,0);//doesnt work, callback is *undefined* in this moment
setInterval(function(){ callback();},100);//does work as callback is just called before being referenced.
var callback=function(){};

why does this code execute my function soon as the document is loaded? [duplicate]

This question already has answers here:
In JavaScript, does it make a difference if I call a function with parentheses?
(5 answers)
Closed 7 years ago.
I'm trying to understand why this code below executes my function as soon as the document is loaded:
var list = document.getElementsByTagName('li');
function yep() {
window.alert('yep');
}
list[0].onclick = yep();
But this does not:
list[0].onclick = yep;
Why does () make a difference when executing a function in this situation?
The parenthesis () execute function immediately. On your second line you are assigning the value of list[0].onclick to the function name but not executing it.
Putting () after a reference to a function means that you want to call the function. Leaving them off means you just want to work with the reference to the function as a value in and of itself.
yep is a reference to a function.
yep() is a directive telling the Javascript engine to execute the yep function.
That's why one executes immediately and the other does not.

Unnamed function in JavaScript doesn't work [duplicate]

This question already has answers here:
jQuery document.ready vs self calling anonymous function
(5 answers)
Closed 8 years ago.
I have tested something and it was really strange...
When I use:
jQuery(document).ready(function ($){
console.log($('.box').length);
});
the return value is 4;
If I use this:
(function ($){
console.log($('.box').length);
})(jQuery);
the return value is 0;
(in the same document)
Any explanation for that?
(I have tried to reproduce in jsfiddle but both return same value.)
Your second example will cause the code in the function to run when the whole overall statement is parsed. The jQuery version waits until the DOM has been fully parsed and populated. The two pieces of code are simply different, in other words.

How is this Javascript called? [duplicate]

This question already has answers here:
What does $(function() {} ); do?
(6 answers)
Closed 9 years ago.
I find the following code in an html document:
<script type="text/javascript">
$(function () {
...
});
I cannot see any intrinsic events like onload = and would like to know how this code is called?
What is the real name and scope of this function and can I call any function defined inside? How?
Whenever you see $ before a function, or $(...).function(...) that usually denotes jQuery.
In the following fiddle I use this code, which is executed on load:
$(function () {
alert("hi!");
});
See here: http://jsfiddle.net/VMZkW/
It is just an anonymous function . In javascript you don't really need to give it a name and because of that after executing once you can never refer it again.
You can have anonymous functions that can be used several times, but not this one. To reuse an anonymous function you just return it to something.
And being an annonymous function it does not create any scope or naming issues and it can access everything according to where it is defined. So you can call outer function too from inside.

Categories

Resources