Two confusing statements, which one to use and why? - javascript

I am confused about these two statements. Both are giving two different results. For simplification I am not posting full code here. The key point is I want to know the difference between the two. say, I want to invoke a function when I scroll the page. What is the difference between using a parentheses and not using a parentheses in this statement?
window.onscroll=function_Name;
And
window.onscroll=function_Name();

With parenthesis means: run the function and return the result.
Without parenthesis means: use the function itself.
So if you want to bind a function to the "onscroll" event, you do NOT want parenthesis. For example, if your function returns "2", then
window.onscroll=function_Name();
would be the same as
window.onscroll="2";
which wouldn't make sense.

window.onscroll needs to be a function. If function_Name is a function, then the first form would be the one you'd normally use. function_Name() executes the function, so the only way the second thing is legal is if function_Name returned a function as a result (for example, generateScrollHandler might be a good name for such a function-returning function). But if it returns, say, 5, then window.onscroll becomes 5, which makes no sense at all.

The parenthesis used in "window.onscroll()" means that the function is being called by the scroll event, without the parenthesis, the script will not know that it is supposed to run the code, in stead it will try and call a variable, or it will do nothing.

Related

Immediately Invoked Function Expression: Where to put the parenthesis?

I've seen IIFE's written:
(function() {
console.log("do cool stuff");
})();
as well as:
(function() {
console.log("do more cool stuff");
}());
They seem to work the same in any context I've used them, though in cases I've been told one way is right and the other is wrong, vice versa. Does anyone have any solid reason or logic as to it being written one order over the other? Is there some cases where there could be potentially more going on after the function body closes but before the invoking parenthesis come into play, or after but before that final closing parenthesis? I've mostly used these in an Angular module closures and can't seem to find anything on any real reason to go one way or the other, wondering if anyone had different experience.
Short answer: It doesn't matter, as long as you put them there.
Long answer: It doesn't matter except in the case of arrow functions, because for JavaScript the only important thing is that they are there. The reason for this is that the language spec defines that a statement must only start with the function keyword if you declare a named function. Hence, it is against the spec to define an IIFE like that:
function () {}();
The workaround for this is to wrap the entire thing in parentheses, so that the statement does not start with the function keyword anymore. You achieve this by using
(function () {})();
as well as by using:
(function () {}());
Which one you choose is completely arbitrary and hence up to you.
I (personally) put the parentheses around the function, not around the call, i.e. like this one:
(function () {})();
Reason: I want to use the smallest portion of code to be wrapped in something that is only needed for technical reasons, and this is the function definition, not the call. Apart from that the spec says that you can not define a function in that way, it is not about calling the function. Hence, I think it's more clear if you wrap the definition, not the call.
edit
However, in the case of the arrow function in es6, the invocation must be outside of the wrapper. It being inside the wrapper causes an unexpected token error on the opening parenthesis of the invocation. Not totally clear on the mechanics of why this is so.

javascript: reason for declaring and immedieatly calling inline function

So I had an interview where I was asking the purpose of declaring and calling a function immideately, and i couldn't answer it, i.e:
(function(){
// code
})();
What's the reason for doing this?
Object-Oriented JavaScript - Second Edition: One good application of immediate (self-invoking) anonymous functions
is when you want to have some work done without creating extra global
variables. A drawback, of course, is that you cannot execute the same
function twice. This makes immediate functions best suited for one-off
or initialization tasks.
The syntax may look a little scary at first, but all you do is simply
place a function expression inside parentheses followed by another set
of parentheses. The second set says "execute now" and is also the
place to put any arguments that your anonymous function might accept:
(function() {
})();
or
(function() {
}());
are the same:

What is the purpose of anonymous Functions in Javascript/JQuery when it seems I don't need one?

Let me explain this a little better. I've just started learning JS and Jquery coming from learning java/c for a short while. I'm use to the functions (methods) in those languages and am having a difficult time understanding why certain functions are used in JS. I've read all sorts of tutorials and searched this site but the answers for "why anonymous functions are used" is different than what I'm looking for.
For example:
$(document).ready(function() {
$('div').hide();
});
Here with the use of jquery we are hiding the "div" elements with a function. Or here:
$('div').click(function() {
$('div').hide();
});
The same thing here except when we click on the div it hides it. But here's the thing I'm confused about - why does it need be on click, then a function running ".hide()" as opposed to just every time on click it just does "('div').hide();"
Or with the first piece of code you just want the 'div' elements hidden, why isn't it just simply hiding the elements with $('div').hide() - why is there the need of a function to do this? You don't need to call the function anywhere else. It just hides it when the document is ready, or with the first example, it hides when you click it.
I've seen this in the practice tutorials on codeacademy and other tutorial videos many times so far, where there are functions that I don't think are needed but are used.
Finally, even a function with a variable like this:
$('#add').click(
function() {
var value = $('#inp').val();
$('#shoplist').append('<li>' + value + ' </li>');
}
);
On click it adds a list element to the unordered list, but i don't understand what the need for function() {} is. .click() already makes something happen on click, we run code inside it to happen on click, why does it need a function() as well to make the code inside work?
why does it need be on click, then a function running ".hide()" as opposed to just every time on click it just does "('div').hide();"
You have to pass something to click.
That something is "The function you want to run when the click event happens"
If you instead did:
...click( $('div').hide() )
then you would:
Call hide() immediately (because that is what $('div').hide() does when it is evaluated)
Pass the return value to click.
The return value isn't a function, so it would either error or be ignored, and clicking would do nothing.
The function you pass to click doesn't need to be anonymous, but it does need to be a function.
This would be fine, for example:
function hide_div() {
$('div').hide();
}
...click(hide_div)
The .click function takes a function callback as a parameter. You're telling it what to run when the click event occurs.
You couldn't pass the code inside the anonymous function to the .click function because it is expecting a function callback.
Lines of code are run in functions, and lines of code are executed when they are called on. When you do this .click($('div').hide()), you're calling the function .hide() on $('div'), giving the result of this function to .click(), as opposed to giving this unevaluated line of code to the .click() function. Protip, whenever you see (), some function is executed unless this function is being declared. In this case, .click() is an execution of the function that has been declared as function click(var callback).
There does not exist a single language (that I can think of) where you can actually pass parsed lines of executable code to another function, that are not encapsulated by a method or function. This is simply so because lines of code do not have a type, or definition. How would you define a 'couple of lines of executable code' in a function somewhere?
I challenge you to define a function that does this, and I BET you will either create a function that accepts another function as a parameter, like click(var callback), OR that you will define some sort of parser that tries to parse the lines of code to executable JavaScript and then evaluate it, which is the same as an interpreter, which is what is used to run JavaScript to begin with.

Javascript/jQuery function arguments

Newbie jQuery / Javascript question here
I see functions written in the following fashion:
some_function = function(event) {
}
My question is: What is meant by that event argument? Is it optional? What if I want to have two additional parameters, X and Y, what would the signature look like? When I call the function now, I can just call it like some_function(); and it works fine (which leads me to believe that it's optional). However, how will that change when I have two additional arguments like X and Y? Can I just call it like some_function(myX, myY) ?
Thanks!
There are two ways to instantiate a function in JavaScript. They both look the same, but their meanings aren't quite the same.
What you've posted is a function instantiation as part of an expression in the language. In that form, the syntax is
function name ( p1, p2, ... ) { body }
The "name" and the parameters are optional; the keyword function and the parentheses are required. (There are some obscure issues with using a name in this case, in some browsers; it's getting to be less of a problem.)
The effect of that is to create a new function object. The reference to the object participates in the expression just like any other value (well, like any other reference to an object). Because it's a function, the reference can also be used to call the function and cause its code ("body") to execute, just like you'd expect. (It wouldn't be much of a function if you couldn't!)
The other way a function can be instantiated is with a function declaration statement, which looks, surprisingly, exactly the same (except that "name" is required). The difference involves where exactly in your code the keyword function appears:
If the keyword function is the first thing in a new statement, then you've got a function declaration and the "name" is required. The statement is not an expression statement in this case, and the only thing the statement does is instantiate the function and bind a reference to the function to "name" more or less as if "name" were a local variable (or global if in the global scope).
If the keyword function appears anywhere else in an expression (either an expression statement, or an expression buried inside some other context, like the top of a for or while loop statement), then it's a function instantiation expression.
Now, regardless of how a function is "born", once you've got a reference to the function you can call it and pass as many parameters as you like.
I don't know personally how the trend started, or whether it's even something that should be considered a trend, but it's fairly common to see local functions instantiated with code like this (and like what you posted):
var some_function = function( arg1, arg2 ) {
/* some code */
};
That's an example of a function instantiation in an expression. The net effect is that the symbol "some_function" is bound to the newly-created function. There are slight nitpicky differences, however, between the way that name is bound to the function from the (almost) equivalent function declaration:
function some_function( arg1, arg2 ) {
/* some code */
};
One simple reason that the second way (function declaration statement) is a little better is that the name of the function will show up in stack traces. Of course, one could achieve that with the redundant-looking:
var some_function = function some_function( arg1, arg2 ) {
/* some function */
};
I don't really know why you'd want to do that, but it'd work, except in some naughty environments.
That code snippet is a little vague, however I can answer, in general, your questions.
The event argument, in the code you provided, is just what that function will use to reference the first parameter that is passed to the function from whatever-other code calls it. For example, if you had code that called your some_function function, and passed it a string "hello world!", the call would look something like:
obj.some_function("hello world!")
Inside of the some_function function, the variable event would contain "hello world!". Also, you could change your some_function signature to be: some_function(blah) and it would be all the same, you would just use blah to reference the parameter instead of event. The variable name you choose for parameters is entirely up to you, though you want to make sure you don't use language-reserved names (like in, for, continue, break, etc)
Technically all parameters are optional for a JavaScript function, unless the internal code of the function enforces the parameters (i.e. it may return or throw an error if a parameter is missing.
#Pointy answered the other point I was going to make...that the code you provided is defining that function as an expression. I use that syntax when I'm creating a function that is an attribute of an object (which is why my above code has obj. at the beginning.

JQuery\Javascript - Passing a function as a variable

I was just curious if I could pass a function as a variable. For example:
I have a function
$('#validate').makeFloat({x:671,y:70,limitY:700});
I would like to do something like this:
$('#validate').makeFloat({x:function(){ return $("#tabs").offset().left+$("#tabs").width();},y:70,limitY:700});
This does not work, but ideally every time the variable was accessed it would compute the new value. So if the window was resized it would automatically adjust as opposed to a variable passed in being static. I realize I can implement this directly inside the function\widget, but I was wondering if there was some way to do something like the above.
The concept of this is independent of the plugin. I am talking about the function being "cast" as a variable.
Yes, you can pass an object which will invoke some function when its property is read (this is called a getter), but it is not cross-browser compatible. For example, this will (probably) work in IE9:
var o = {y:70, limitY:700};
Object.defineProperty(o, 'x', {get: function() {return 671;}});
$('#validate').makeFloat(o);
There are other syntaxes for other browsers such as __defineGetter__ for Firefox, and some browsers don't have this functionality at all. So it is practically useless unless you can fully control the environment where your code runs.
This won't work unless x is invoked (obj.x(), instead of just obj.x).
To make it work, the makeFloat() code must check the type of x, and if it's a function, invoke it.
I see what you're trying to do, but it won't work. Why? makeFloat expects the value to be non-function type. It probably uses that value directly. To actually execute the function, makeFloat needs to do x() or even x.call(...) or x.apply(...), which it most certainly isn't doing.
To answer your other question i.e., can you pass functions as variables, the answer is yes. In fact, this is the way callbacks and closures are handled in Javascript. For example, in jQuery when you bind an event handler you are passing in a function as a parameter:
jQuery("#myInputId").click(function() {
...
...
});
Another way that parameters are passed in are as object attributes, for example in jQuery.ajax:
jQuery.ajax({
...
success: function(data) {
},
...
});
In both cases, click and ajax both understand and expect the parameter to be a function and not just a regular variable. For example, assuming you had an object that maintained a list of integers and you had a method called addElement(int), which expected an int parameter, you wouldn't pass in a String. It works the same way in Javascript, except for the fact that the language is not strongly typed. This is why you don't really get a type-mismatch error unless the function explicitly checks the type and throws an exception. This is generally a good practice in such language; I try to do this in the Javascript code that I write.
I've done this with string variables. You'll need to exploit the toString function.
function RefString(fn) { this.toString = function() { return String(fn()); }; }
You can use it like so:
$("#someDiv").somePlugin({optionValue: new RefString(MyFunc), ... });
function MyFunc() {
return new Date().getYear().toString();
}
It works by setting optionValue to a new OBJECT, not necessarily a function. Then anything that reads this object will ask for a value, which by default is the result of the toString function. We simply override the default behavior by executing a function that is specified when the object is constructed.
I'm not sure how it will work for EVERY plugin, but it works when a string or number is expected.
How do you mean "doesn't work"?
It looks like it should compile and run. But what happens is it executes the function and sets the value no different than if you used a constant, or called a function that wasn't inline.
What you need to do is put this line of code in an event that fires when the window is re-sized.
It looks like makeFloat is from a jQuery plugin - are you sure that the plugin is aware that 'x' can be a function and will execute it properly? From the jQuery site, it looks like it only is able to comprehend a number value or 'current' as a string, not a function.
You can pass functions as variables, yes - but that's not actually what you're asking.
What it looks like your asking is "can I set a DOM property to the result of an expression?" to which the answer is "no". (Note - not outside of browser-specific behavior such as IE's CSS Expressions - which have been deprecated in IE8 anyway)
You'll need to bind an event handler to window.onresize and use a function to update the sizing yourself.
In order for a function to be executed from a variable, it has to be called, like so:
$.option.callback.call();
Where option is the containing variable, callback is the function and call executes the function.
It's not like you don't have options though. You can set it up so that the returned value of that function is executed from the line itself. Or you can set it up in the alternative manner that you described.
You need to invoke that function so that it returns the actual value you're looking for. So you're not actually passing in a function, you're invoking it and it's immediately returning a value. For example:
$('#validate').makeFloat({
x:function(){
return $("#tabs").offset().left+$("#tabs").width();
}(),
y:70,
limitY:700
});
Notice the extra () after the function call. This invokes the function immediately, thus returning the value you're looking for.
Note that x doesn't "compute new value" when is accessed (read), but when the function is called, i.e. x(). As Chad mentioned, this is how you can automatically execute a function when windows is resized:
$(window).resize(function() {
// do something
});
[Update] After re-reading your question, I think you may be thinking overcomplicated – isn't this what you are looking for?
$('#validate').makeFloat({
x: $("#tabs").offset().left + $("#tabs").width(),
y: 70,
limitY: 700
});

Categories

Resources