Passing an array as the code to eval in setTimeout? - javascript

Today my friends sent my some code that did something unexpected:
setTimeout(["console.log(1", "2)"], 1000)
I expected this to fail or do some magic, but it just prints 1 2 after 1 second.
I can see it possibly evaluating the array to "console.log(1,2)" using a simple array.join(','), but why does that happen?
I've looked into the eval capabilities of setTimeout, but it should only do a function or a string. The use of an array here doesn't make any sense, and searching Google for why this does work turns up nothing, or even close use cases.

setTimeout can evaluate a string as javascript, if the value is not a function it will then convert the value to a string, probably by using toString()
You can see if you do this
"" + ["console.log(1", "2)"]
or
["console.log(1", "2)"].toString();
you get
'console.log(1,2)'
Then it get's evaluated accordingly

If it is not a function then it uses .toString() to get a string value.

Related

Difference between eval() and eval`` (with backticks)

So I have came across a curious question that I can't find its answer anywhere and there isn't much documentation on what eval does when you pass to it string literals.
If I do eval("alert(1)") I will get an alert box with 1, however, when I do eval`alert(1)` I just get an array with "alert(1)" I am not sure where that is coming from, isn't it supposed to be treated the same as the previous example?
Also, eval`${1}` returns an array with two empty elements, why?
What you're running into is something to do with tagged templates.
Essentially, you are doing string interpolation and using a function to decide how to create the string. The first argument is expected to be an Array that contains all of the string parts (everything between ${var} declarations). The return of any function used this way is expected to be the string. The reason you are seeing 2 entries is because this function returns a raw format in addition to the one it tried to create using the tag function.

assignment in JS

This is a very basic JS question, but this "issue" drives me crazy.
From simple algebra I would expect that both first and the second statement are vaild. But the second is always throwing "Invalid assignment" error.
Does anyone have a good explanation for it?
fieldname1 = document.getElementById("emailID1");
document.getElementById("emailID2") = fieldname2;
Thanks so much,
Most common programming languages, including JavaScript, require that the left-hand side of an assignment (the "target") be something called an l-value. That means it's an expression that denotes a place to put a value. A simple variable name, or a reference to an object followed by .propertyName suffix, works as an l-value.
In your case, the function call return value is not an l-value, because JavaScript does not make that possible (some languages do). A function call is always an r-value, meaning something that appears on the right-hand side of an assignment.
Now, in your particular case, because getElementById() returns a reference to a DOM element, you can do something like this:
document.getElementById("something").name = "frederick";
The function still returns an r-value, but that .name works as a property reference and thus as an l-value.
The assignment operator resolves the right side of the equal sign and stores it in the variable on the left side, which is what is happening in the first line.
The second line is basically trying to take the value of a variable fieldname2 and store it in a function call document.getElementById("emailID2")
JavaScript doesn't know how to resolve that at runtime, so it's throwing an invalid assignment operation.
There's more information on assignment from MDN here:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Assignment_Operators
You can't assign a value to an object itself in this case.
document.getElementById("emailID2") = fieldname2;
As i guess you want to do something like this:
document.getElementById("emailID2").name = fieldname2;

console.log() showing contradictory values for the same object property

I think i might be going mad.
I use console.log() to see the state of an object and then on the next line do a console.log() on a particular property of the same object and get different values for each.
The code i'm using is:
console.log(this.pictures.Items[pic].val);
for(var i in this.pictures.Items[pic].val) {
console.log("property: %s, value: %s", i, this.pictures.Items[pic].val[i] );
}
and firebug outputs:
Picture { isLoaded=true, isSelected=false, img_src="imgs/image1.jpg", more...}
property: isLoaded, value: false
...more properties
as you can see, 'isLoaded' is true when logging the object itself but false when logging the property.
I have tried logging the object again after just in case, and it is true again.
Does anyone know what is happening here?
Thanks
Rich
I'm not entirely sure if this is what is happening to you or not, but console.log() seems to have some issues in some browsers where doing a console.log() on a value or using an index variable that is changing or being iterated in an array does not always work properly.
My guess is that it has something to do with things getting marshalled between process boundaries and perhaps a delay in the actual evaluation of the logging expression until a time in which the actual object or index being used or referenced has changed. I've seen this issue in Chrome for sure - don't know about Firefox.
You should be able to work around this particular issue by using string math to build your final string. If only the final string is passed to console.log() where everything is fully evaluated, then this issue would not impact the output.

Writing my own split method

I found out earlier today that split() doesn't work if attached to a single value.
I would like to write my own split() method so that if I sent it a single value, it creates an array with a single value.
Q: Should I change the split prototype or write a function?
var SPLIT=function(X) {
return X.toString().split()
}
To clarify, split() does work with a "single value". The problem in your last question was that the value returned was not a string, and hence the .toString() is necessary.
In my opinion, there's no need to write another function for this. Simply remember to convert your values to a string before calling .split() on it.
If you must have a function that does this, then to answer your question, create a new function and don't modify the prototype. While it may seem harmless to modify the prototype of Number or Object in this case, it's generally considered bad practice as other code (e.g. libraries you're using) may not be expecting it.

Settimeout function in Firefox does not seem to work

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

Categories