I'm having this weird behavior and I'm not sure if it's me not misunderstanding variables or it's an xpage issue
I have a document with a field called "hours" and it has a value of 8.
Here is my simplified code .
var xHrs = doc.getItemValueDouble('hours');
println (xHrs); // at this point, hours is 8
doc.replaceItemValue('hours', 0);
return xHrs; // returns 0;
Why is xHrs back to 0 when I replace the document value to 0? How do I break the link?
Thanks in advance for the help :)
R.
Chances are that the code is being executed more than once.
Try wrapping the code with ${javascript: rather than #{javascript:
${javascript:
var xHrs = doc.getItemValueDouble('hours');
doc.replaceItemValue('hours', 0);
return xHrs;
}
The code will be executed only once with the preceding $.
I suspect that setting your xHrs variable as you do creates a function expression that returns the value of the 'hours' field. You change the value of the field and the function returns the new value.
I'm not sure about breaking the chain in an efficient manner, but maybe if you create a second variable to hold the xHrs value?
Related
I have been recently reading function expression and declaration in javascript and have referred to quite a few online articles about this. I also have seen quite a few discussion about this topic on SO. In the process of learning I tasked myself with a challenge, which I am not able to clearly explain.
Can I kindly request SO experts to help me gain some insight here?
Here is the problem scenario -
Scenario 1:
>var multFunc=function(n){var a=2; return n*a;}
>multFunc(6)
12
I understand this scenario and the result is what I was expecting (12).
Scenario 2:
>var multFunc1=function(n){return function(n){n*2}}
>multFunc1(6)
function (n){n*2}
I did not understand the second case. Why would it not return 12?
Can someone please help me understand this?
I have checked this link - Javascript Function Expressions, this link JavaScript Nested function
and I also did ask a similar question yesterday, but I guess I did not fully grasp the concept (as explained graciously by T.J) -
Trying a closure the wrong way?
The code:
var multFunc1=function(n){return function(n){n*2}}
returns a function. So multFunc1 represents the returned function, in this case:
function(n){n*2}
so you had to call like:
multFunc1(1)(2)
So basically the returned function remembers the value of n (passed argument, I recommend you to read about closures). So we can re-write the calls like:
var multFunc1=function(n){return function(x){n*x}}
var multBy2 = multFunc1(2)
var multBy16 = multFunc1(16)
multBy2(4) // 8
multBy16(2) // 32
Side note: The multFunc1's inner function, doesn't have any return statement, so it always returns undefined as #nnnnnn pointed out in comments
What you are essentially doing here in the second scenario is returning the function Object. Rather than returning the result of the execution of the function (which would be usually be 12) you are just returning the Reference to that object.
UPDATE:
I think you are missing the return statement inside the second function. By adding so, this yeilds the result I believe you are looking for.
var multFunc1=function(n){
return function(n){ return n*2}
}
// The first set of () require no argument as
// they are never used withing the second function.
multFunc1()(6);
While reading source code, I saw a line
console.log(setTimeout("1"))
and this code has return a random number.
I don't know why. Please help me.
As per MDN,
The returned timeoutID is a numeric, non-zero value which identifies the timer created by the call to setTimeout(); this value can be passed to Window.clearTimeout() to cancel the timeout.
So when you do = setTimeout(), you are not getting value of something that you have passed, but it a system generated identifier.
setTimeout registers an event in event heap after specified delay. If delay is not mentioned, it assumes as 0 but note, setTimeout(notify, 0) is not same as notify().
Also setTimeout expects a function as first parameter. When it receives a string, it assumes, you are passing function call as string and compiler tries to evaluate it using eval. So your setTimeout("1") will become eval("1") which will return "1" and hence you do not get error.
function notify(){
console.log('ta-da!!!');
}
var a = 10;
setTimeout("notify()",0)
// sample for eval
console.log(setTimeout("a"))
// This should throw error as `b` is not declared
console.log(setTimeout("b"))
I'm having problems with some javascript code that I can't seem to figure out. The function I use is
var tagline = new function(){
document.write(
tags[
Math.floor(Math.random()*10)
]
);
};
which calls on an array of 10 strings called "tags" and displays a random entry from that array.
The problem is that for some reason the function executes even when it isn't called, and when I do call it nothing happens. The function just puts the text in the top left corner and does nothing different whether it is or isn't called. This is especially a problem with the styling, because no matter what I do I can't change the position, size, etc. of the text.
(Yes, I'm aware I can do the same thing with
document.getElementById("tag").innerHTML = tags[Math.floor(Math.random()*10)] ;
but I like to write my own functions.)
Thank you for any help you can give!
It's because you use the new keyword. Remove that so it becomes:
var tagline = function(){
By using the new keyword, you are instantiating a new object from the function, which immediately calls it, and your variable then contains the object, not the function, which explains why you can't call it after it first executes.
Not sure if this is considered best practice or if you should even do this but I have a small block of Javascript and I want to know if you can declare a variable, display that variable and then reassign it and display it again? Syntactically this seems correct but I would assume that this is not best practice and should be avoided?
Note: I did not write this block I just want to know if it's ok or if I should change it and use 2 variables code below:
var u1 = 'something';
if (u1.indexOf('Accept') > 0)
{
var URL = 'some URL';
document.writeln(URL);
URL = 'another URL';
document.writeln(URL);
}
Thanks in advance.
EDIT:Thanks for the answers, thought it was a bit daft. :/
Yes you can
You can change variable's value as many times as you need to. Variables are quite often reused so we save memory resources. Not in the way you've used them (because that's an example that would be better off providing constant strings directly when calling functions) but think of an everyday example where we don't even think of multiple variable value assignments. A for loop:
for (var i = 0; i < 100; i++)
{
...
}
In this loop variable i gets assigned a new value 101 times. This is a rather obvious example, where we don't think of this at all, but other than that, we could have a set of loops and reuse the same variable more explicitly and assign it a value lots of times like:
var counter = 0;
for(var item = GetLinkedListFirstItem(); item != null; item = item.Next)
{
counter++;
}
// other code...
counter = 0;
while (counter < 10 || someOtherCondition)
{
// do something else
}
This may be a much better example of explicit variable reusability where its value gets changed lots of times and for different purposes.
Variable naming
Variable reuse is sometimes unwanted/undesired. And that's when we have a meaningful variable name like isUserLoggedIn. It's hard to reuse such variable for other purposes because it would make code unmaintainable.
Variables that are usually reused may hence be iterators (ie. i) or generally named variables without too much meaning. Or variables with more universal name (ie. finished) which can be reused in different contexts that can be associated with such variable name.
Asynchronous code
There are certain situations where you may have problems even though looking at code may seem perfectly fine. And that's when you use async functions which is frequently the case when using Ajax calls or time-deferred calls (ie. setTimeout). Consider the following code:
var loaded = false;
$.ajax({
url: "...",
type: "POST",
success: function(){
loaded = true;
}
});
if (loaded === true)
{
// do something important
}
// ok loaded not used any more, so we can reuse it
// we can easily change its type from number to string or anything else
loaded = "Peter loaded his gun";
This code has a bug, because important code won't be executed. Ever! This is quite a frequent misconception by unsavvy developers not understanding asynchronism.
Hint: When code issues an Ajax call it doesn't wait for a response but rather continues execution and executes if statement. Even though Ajax call would respond in 0time ticks, success function wouldn't execute until this currently running code wouldn't finish execution. That's how Javascript works. Queued code execution. In the end when Ajax async code would execute it would eventually overwrite the string that was stored in the variable.
Why not? Of course, it's normal to change variable value as much times as you want. That's actually reason why it's called "variable", not "constant" :)
I'd say it's perfectly fine to do so.
However, keep in mind that it can cause problems with asynchronous code. Take the following example for instance, where async accepts a callback that runs some time later:
var a = 123;
async(function() {
alert(a); // alerts 456, because `a` was set to 456
// *before* this callback was run.
// Because there is only one `a`, that variable
// has been overridden
});
a = 456;
async(function() {
alert(a); // alerts 456
});
Yes it is possible, and in this case there is no point in creating a new variable. However, if you have a lot of code reassigning a variable later could definitely be confusing especially if at first it's an object then later it is a string.
Variables can be reassigned in JavaScript. Whether they should or not is a question of style and context.
I normally prefer to re-use variables rather than create new ones
Is there a way to make the following work?
function TimerEvent()
{
TIMER_OBJ = setTimeout('Ajaxsessioncheck();', '<%=Timer%>');
}
I am calling this function in the onload event but it is not calling the Ajaxsessioncheck function when the time has elapsed in Firefox. In IE and Chrome it works fine.
thanks for all for ur time.. i changed the code as sent timer as integer now i have a different problem. In the Ajaxsessioncheck() function i wil call a JSP page from i am not getting Response in Firefox.
You've specified '<%=Timer%>' as a string (denoted by the single quotes), where it should be an integer, like so: <%=Timer%>
You should also specify the first argument as a function reference rather than a string, so your final output would be:
setTimeout(Ajaxsessioncheck, <%=Timer%>);
you shouldn't pass the second parameter as string.
TIMER_OBJ = setTimeout('Ajaxsessioncheck();', <%=Timer%>);
should work fine. but to be even more correct, you should also avoid passing the first parameter as string, because otherwise is gets evaluated - a hidden execution of eval happens, and eval is evil. therefore, this is what you want:
TIMER_OBJ = setTimeout(Ajaxsessioncheck, <%=Timer%>);
PS. declaring a variable without using keyword var causes it to leak to the global scope. I'm not sure if you're aware of this fact.
'<%=Timer%>' is a string - it should be an int in milliseconds.
Almost all questions starting with X does not work in Y comes down to differences in browser implementation. Similar to
document.getElementById does not work in firefox and the element has a name but no ID. Works in IE but not in Fx