var is firing before triggering through button - javascript

Let's say I have the following situation:
CLICK ME
and
var x = alert("test");
$('#trigger').click(function() {
x
});
Why is x firing on loading the page, and not while pressing the button? I know when placing the variable into the function it works, but I don't really get why!

var x = alert("test");
This will execute alert("test"), then assign the value of that expression to x. (alert doesn't return anything, so x will be set to undefined.)
Instead, use this code:
var x = function() {
alert("test");
}
$('#trigger').click(function() {
x(); //remember to actually call it!
});
Here are some better ways:
$('#trigger').click(x); //no need to wrap in function if it does not have
//any arguments
$('#trigger').on('click', x); //using on

In this line
var x = alert("test");
you actually call the function and put its return value into the variable x. As alert() has no return value besides undefined there is nothing really stored in x.
That's why the next time you access x it is still empty and does not contain a pointer to a function or something similar!

var x = alert("test"); will call the function alert("test") immediately, and then assign the return value to x.
To get the behavior you desire, you can wrap the call to alert in a function:
var x = function() {
alert("test");
}
And then to call it later, use parentheses (a parameter list):
$('#trigger').click(function() {
x();
});

Because alert("test") is a function which will show an alert message. Since you call this function not in the $('#trigger') area, it has nothing to do with the click functionality of the trigger but will be executed as soon as the script part is executed by your browser.

Related

Global and Local variables JavaScript

How to get information that is inside a function, from outside a function
var x = 0;
function myFunction() {
x += 1 //When a button is clicked Javascript will add 1 to x, now x will have a value of 1
}
alert(x) //This returns 0, how to make it return 1
P.S Only pure JavaScript
P.P.S Try to make your answer simple, without a lot of code. Thanks :)
You have to call myFunction() first, e.g.:
myFunction();
alert(x);
It should be called myFunction, myFunction(), first before the alert. This is why you get 0. When this script is loaded the value of x is 0. Hence the alert will alert 0. Then each time a user clicks on the button you have referred to, the value of x would be incremented by 1. That being said, I think that you need something like this:
function myFunction() {
// when the button will be clicked the value of x
// would be incremented by one.
x += 1
// the new value would be alerted.
alert(x);
}
Another way it would be this:
myFunction();
alert(x);
However, this doesn't make sense, since you need to increment the value of x each time the button is clicked and you don't need to force the execution of myFunction.
Well, your function has to be executed for that. The function body only executes if invoked/called. So either create an IIFE function or call it later
myFunction();
alert(x); // now the value has been updated
By IIFE (Immediately Invoked Function Expresson), I mean
(function(){
x += 1;
})(); // invoke
start by colling your myFunction(); and then you can get the value by alert(x);
The other answers are correct in this situation - just call myFunction(); before alert(x), but just for completeness, the other option to "get information inside a function from outside it" is to return a value from the function:
var x = 0;
function myFunction() {
return x + 1; // returns 0 + 1 = 1. Note x is still 0
}
var y = myFunction(); // y stores the return value of the function, i.e. 1
alert(y);
Check out:
http://jsfiddle.net/4taojgy7/
(function(){
var x=10;
function run(){
alert(x);
}
run();
})();
Function 'run' can access only those variables which is in its scope. Even though variable 'x' defined in outside, but still it is accessible. You need to look into scope of a variable concept more. Hope that clarifies.

Variable undefined when set inside a function

function setx(){
var x = 'foobary bazer'
showit();
}
function showit(){
console.log(x);
}
setx();
In the above example, the showit function fails because x is undefined. However, x is set and is available in memory (or so I thought) before showit is called. Why is this not the case?
Also, what's the best way to make this code work, so the console.log does indeed print foobary bazer to the console? I could get rid of the var and make it a global, but I don't think this is the best way as it can cause strange bugs.
You could pass the x variable to the showit function:
function setx(){
var x = 'foobary bazer'
showit(x);
}
function showit(x){
console.log(x);
}
setx();

Execute Jquery every time a specific function runs [duplicate]

This question already has answers here:
do something when function executes Jquery
(2 answers)
Closed 9 years ago.
Is it possible to execute something every time a specific function runs without any knowledge about that function besides its name?
This would be similar to bind
var clicked = 0;
$('#foo').bind('click',function(){
clicked += 1;
alert(clicked);
});
So there, every time something with the ID foo is clicked, it will add 1 to the variable clicked so that I know how many times it has been clicked. What I want to do would be the equivalent of the following if it were correct syntax:
var fired = 0;
$('my_function').bind('run',function(){
fired += 1;
alert(fired);
});
I don't care if in any given situation you would be in, you would always be able to figure something out about the function and use that, I don't want work arounds, this is what I want for an answer:
How I can execute something everytime a specific function runs, just given the name of the function. If that is not possible, why not?
Try something like this:
var temp = my_function, fired = 0;
my_function = function() {
fired++;
temp.apply(this,arguments);
}
I think something like this may be the closest you can come:
function adjustFunctionToCount(f){
var count = 0;
function newF(){
count++;
f.apply(this, arguments);
}
newF.getCount = function(){ return count; };
return newF;
}
And so if you have
function handler(val){
console.log('called with val ' + val);
}
You could do
handler = adjustFunctionToCount(handler);
handler('a');
handler('b');
console.log(handler.getCount());
FIDDLE
And needless to say you could create your function inline
var handler = adjustFunctionToCount(function(val){ console.log('called with val ' + val); });
handler('a');
handler('b');
console.log(handler.getCount());
UPDATED FIDDLE
I'm pretty sure that's impossible in the general case.
Remember, functions are objects, really, and the name of a function is just a variable. Functions can exist without being assigned to a named variable, the variables can be out of your scope, or reassigned/swapped around. In any case, I know of no API that lets you hook onto a JS function call.
This may be of interest: Can I intercept a function called directly?
This is where event driven programming comes in - and jQuery makes it really easy to do.
var myFunction = function() {
//...
//...
//...
$(document).trigger('someEvent');
}
$(document).on('someEvent',function() {
//the function you would like to run every time myFunction is called
});
Try this:
var count = (function(){
var c = 0;
return function(){
alert(c++);
};
})();
$('#foo').click(count);
OR
$('#foo').bind('click', count);
When an Anonymous Function or a Variable that represents a Function is passed it is the same thing. You could make your own code that executes a Function like this:
function executeFun(func){
return func();
}
executeFun(count)
executeFun(function(){
/*everything happens in here. The Anonymous Function will be called
automatically because of the parameter next to the variable func above */
})
Although, that example is impractical it shows you what happens internally. Also, I solved your potential global scope variable problem with a Closure. For more on Closures visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Closures .

Why we're not use () at window.onload?

At end of this code (full code is here)
function addSongs() {
var song1 = document.getElementById("song1");
var song2 = document.getElementById("song2");
var song3 = document.getElementById("song3");
song1.innerHTML = "Blue Suede Strings, by Elvis Pagely";
song2.innerHTML = "Great Objects on Fire, by Jerry JSON Lewis";
song3.innerHTML = "I Code the Line, by Johnny JavaScript";
}
window.onload = addSongs;
You will see addSongs didn't used with ().
If i change it as
window.onload = addSongs();
It doesn't works. Why?
when you have addSongs(), it's telling Javascript immediately execute that function and assign the return value of that call to the onload handler.
Without the (), it tells the JS engine to assign the function itself to onload.
e.g. if you had something like
function x() {
return 'hello';
}
// immediately assigns "hello" to the onload
window.onload = x();
which is the same as doing
window.onload = 'hello';
and at some point the JS engine will try to execute a function named "hello", whenever the onload handler is triggered.
addSongs is a function, which you can assign to a variable (namely, in this case, window.onload). On the other hand, addSongs() is calling that function, and therefore you're setting window.onload to whatever addSongs() returns. Which is nothing, in this case.
just like we assign int a = 5;
cuz we now know that a is an int and we can assign it a integer value like
similarly window.onload is a function , u can consider it to be of function type datatype
thus we can assign
window.onload=function(){ .. some code ... }
or we can use
function abc(){ ... some code ...}
window.onload=abc;
When you use addSongs() it executes it right away instead of when it is being called.
Because you're setting onload to be equal to the function.
If you call the function, then you're setting onload to be equal to the return value of the function (in this case, undefined).
Also, you have no control over when onload/onready/onclick/etc fire. That's the point.
You're asking the browser to fire the function when one of those things happen -- not before.

Javascript assign variable to alert

I am wondering Can you assign a variable to alert ? what does it really mean and do ? For example,
var a = alert('test');
I tried it out, and the alert pops up as soon as the page loads where variable a remains 'undefined' when I call it. Aren't we suppose to make it an anonymous function with the alert inside like
var a = function(){ alert('test'); }
If we want to trigger an alert on something? Why does javascript allow you to do that?
var a = alert('test');
Think of this statement like any other variable assignment. In order to perform the assignment, first the right-hand side is evaluated. In this case it's a function call, so the function is called and its return value is obtained. In alert's case, the return value is undefined. It doesn't return anything.
Then the return value is assigned to a, so a ends up with the value undefined.
As a side effect of the statement, an alert message is displayed. That happens as a consequence of calling alert() and getting its return value.
function foo(x) {
return x * 2;
}
var a = foo(3);
This code is structurally similar to the alert call, and would result in a being 6. But then alert() doesn't return a value. It's more like this:
function bar(x) {
return;
}
var a = bar(3);
Now a is undefined.
var a = alert('test');
This says to execute alert('test') and assign the return value from that function to a variable named a.
This would be no different than:
var max = Math.max(1,2,3,4);
where max would end up with the value 4 in it as the return value from executing Math.max(1,2,3,4).
var a = function(){ alert('test'); }
This says to declare an anonymous function and assign that function object to the variable a. Since the function is just declared, it is not executed at this time. You can execute it in the future with a().
You commented:
I am just wondering why javascript allows we to do that if it doesn't really means anything
Well, JavaScript (and any other language, including English) allows you to do a lot of stuff that does not mean anything, as long as the syntax is valid. For example, the snippets bellow also mean nothing:
var a;
a = a; // so what?
function something() { /* nothing */ }
var b = something(); // very similar to your example!
Wouldn't it be less consistent if you could assign from some functions, but not from others? If the language were typed, that would produce an error, but since it's not, what's the problem with it? If they don't return a value, their return is undefined, and nothing breaks if you try to assign that to a variable. So you can make functions that sometimes return something, sometimes not. That can be an advantage if used wisely. It's a feature, not a problem with the language.
If you do:
var a = function(){ alert('test'); }
You can then do:
a();
since you've defined an anonymous function..
alert is a function so you can't assign anything to it, per se.
If you want something to pop up if a variable has a value, you could do something like -
$(document).ready(function() {
if (someVar != undefined) {
alert(someVar);
}
});

Categories

Resources