I want to be able to call a function within an if statement.
For example:
var photo = "yes";
if (photo=="yes") {
capturePhoto();
}
else {
//do nothing
};
This does nothing though. The function is clearly defined above this if statement.
Edit: Wow, downboated to hell! capturePhoto(); was just an example function that didn't really need any more explanation in this scenario?
That should work. Maybe capturePhoto() has a bug?
Insert an alert() or console.log():
var photo = "yes";
if (photo == "yes") {
alert("Thank you StackOverflow, you're a very big gift for all programmers!");
capturePhoto();
} else {
alert("StackOverflow.com must help me!");
}
I'm not seeing any problems here. I used this code and the function call worked. I kept your code and just added a function called capturePhoto().
Are you sure that the code you're using to call the function is firing?
var photo = "yes";
if (photo=="yes")
{
capturePhoto();
}
else
{
//do nothing
};
function capturePhoto()
{
alert("Pop up Message");
}
You probably missed something, a quotation, a semicolon or something like that. I would recommend you to use a debugger like Firebug or even Google Chrome's Web Developer Tool. You will know what's wrong with your code and where it is wrong.
You may take a look at this live code that your code above works: http://jsfiddle.net/ZHbqK/
The code looks fine to me (except you don't need the ; at the end of the last line). Check your error log; perhaps the browser thinks capturePhoto is not defined for some reason. You can also add alert statements to make sure the code is actually running:
var photo = "yes";
alert('Entering if statement');
if (photo=="yes") {
alert('then');
capturePhoto();
} else {
alert('else');
//do nothing
}
When you encounter a situation where it seems like a fundamental language feature is not working, get some more information about what is going on. It is almost never the platform's fault. It is occasionally a misunderstanding of how the feature works (e.g. why does parseInt('031') == 25 ?). It is usually a violation of an assumption you're making about the code that isn't holding up because of a problem elsewhere.
You should also consider using true and false instead of strings that could be manipulated depending on input.
If I had to correct the following code, then I should've done it like this;
var photo = true; // Will capture picture.
if (photo) { // 'true' is a truthy value.
capturePhoto();
} else {
// Do nothing
}
The code that you posted does work.
I copied it and tested it.
Demo: http://jsfiddle.net/Guffa/vraPQ/
The only thing wrong with it that I can see is a semicolon after the closing bracket, but that is only a style problem. It will form an extra empty statement, but that doesn't cause any problems.
Related
I ran into a bug which I finally solved, but why it happen(ed/s) is still beyond me.
I save a variable foo using browser.storage.local.set for a firefox addon that I'm developing. I know that the variable is set, and the apparent bug was relying on some small piece of code that leads to this:
browser.storage.local.get((val) => {
if (val['foo'] === undefined){
console.log('Undefined');
}
else {
console.log('Defined')
}
});
// Outputs `Defined`, which is correct.
However, if I define the callback first, and then I get wrong output.
function checkStoredSettings(val) {
if (val['foo'] === undefined) {
console.log('Undefined')
}
else {
console.log("Defined")
}
}
browser.storage.local.get().then(checkStoredSettings, console.log);
// Outputs `Undefined`, which is incorrect.
//UPDATE
browser.storage.local.get(checkStoredSettings);
// Outputs `Undefined`, which is also incorrect.
Can someone explain what am I not getting here? I have now run the above two codes sequentially (in both orders) in the same scope.
Did you tried something like that ?
browser.storage.local.get('foo').then(console.log)
I don't know this is possible, but I have some special situations requiring it.
//Obj is a class with nothing.
Obj.prototype.v1 = function(){
//this is a normal statement.
//it could be something else
return 3;
}
//or it can be any way to declare a function:
var v1 = function(){return 3};
Obj.prototype.v2 = function(){
return this.v1()+2;
}
How to make it directly returns 3 here? It's like the function v1() is something like pseudocode this.return(3) for v2(), and certainly nothing can be reached after the first return.
If I'm generating the code dynamically and it has to be a return in the second function. (So it can easily get unexpected token for return (return 3).v2(), while trying to get the inside function to be called behaving like it's part of current function.)
Is there anyway to make this.v1() directly cause outside function v2() to return, for the first return it encounters? Preferably by focusing on modifying v1().
Is there anyway to make this.v1() directly cause outside function v2() to return, for the first return it encounters?
The idiomatic solution is to express this logic in v2. For example, you could cause v1 to modify a flag that decides what v2 does:
Obj.prototype.v1 = function(){
this.v1.continue = true; /* XXX: Continue? */
this.v1.continue = false; /* ... or not? */
return 3;
}
Obj.prototype.v2 = function(){
var ret_val = this.v1()+2;
if (!this.v1.continue) {
return;
}
/* XXX: Insert more code here */
}
We're talking about rather basic JavaScript here. Do you have a book?
Preferably by focusing on modifying v1().
I'm sure it's possible to circumvent the control of execution that v2 has when v1 returns in some situations, but that doesn't make it a good idea. Think about how difficult it'll become to debug this code!
For example, you could throw an error which v2 doesn't catch, and catch it further upstream. Such a hideous abuse of throw would be worse than the abuse of goto! Don't modify your code flow in such an unclear manner; it makes maintenance and debugging a nightmare!
I understand the basic concept of double-negation- conversion to bool - this is a question about the specific use before new.
I was looking for a way to detect blob support and came across this check on this page:
try { !!new Blob(); } catch (e) { return false; }
I created an example below to demonstrate the check always failing.
window.onload=function()
{
var inputBox = document.getElementById('inputBox');
try {
!!new Foo15514();
inputBox.value='supported';
} catch (e) {
inputBox.value='not supported';
}
}
<input id='inputBox' type=text/>
Without getting into whether this is a good approach for blob detection or not, the question I have is what is the point of the !! in this case? As far as I can tell it is superfluous, but I thought I would ask in case there is something I am missing.
!!new Foo15514(), new Foo15514(), var j = new Foo15514() all have the same result.
Update
Just to get the ball rolling - one thought I had is that this was done to force the javascript engine to evaluate this rather than skipping it since it has no effect, which seems like a bad approach if that was the case.
In this case, it is indeed superfluous. Using the ! operator twice just casts a value to boolean.
However, the code you read in that bug report is not complete (like a typo). It omitted an important part of what was actually meant. If you check the commit that was made, the picture looks different:
function test() {
try {
return !!new Blob();
} catch (e) {
return false;
}
}
I apologize for this rather BASIC question, but I am at whits end here!
I have a javascript function that I want to run when the page loads... simple right? I have tried putting the function in doc readys, window readys, putting it before and after the main function, etc etc. NOTHING seems to work.
Code so far:
function calcme() {
DA FUNCTON
}
$(document).ready(function(){
calcme();
$("input").bind("keyup", calcme);
});
Please note... the keyup bind DOES work, but I need the calcme function to load on page load. Thoughts?
UPDATE: As per request, here is the full fiddle. http://jsfiddle.net/vpsSA/
Problem found: The calcme() function assumes it is called from the context of one of the inputs and uses this.value inside. So, when you call it without any arguments, it obviously fails. This can be solved by trigger the keyup of each of your inputs, instead of calling calcme() directly. See the fiddle below.
Working fiddle: http://jsfiddle.net/vpsSA/1/
In your ready() handler, the bind statement comes after the caclme() call. And as you mentioned the event binding worked. This means:
a) calcme() was definitely executed on load. There is no other way since you've mentioned that the binding statement which comes after the calcme() call worked as expected.
b) calcme() did not throw any JS errors - if so, it would have stopped at the error and the event binding would not have taken place. Maybe it threw a warning, which you'll be able to see in your JS console.
c) Since you haven't provided whats inside calcme(), we can't say for sure. But what it looks like is some sort of condition failure because of which you did not get the expected result from calcme() when running on load. Are you using anything inside calcme() thats initialized after running it on load. I would suggest putting in a debugger; statement as the first line in your ready() handler and tracing it in Firebug or Chrome.
try this:
function calcme() {
try {
//your code
}
catch(e) {
alert('error: ' + e);
}
}
if (typeof $ === undefined)) {
alert('not jquery');
}
$(document).ready(function(){
if (typeof calcme === undefined) {
alert('calcme not exist');
}
else {
calcme();
$("input").bind("keyup", calcme);
}
});
I have this piece of javascript:
if(this.isShown || event.isDefaultPrevented()){
return;
}
And I tried to convert it into Coffeescript but I can't seem to get the null return to work:
if #isShown or event.isDefaultPrevented()
return;
How can I get it working properly?
It appears that the CoffeeScript compiler won't implicitly return null unless it needs to to prevent later code from executing. If something happend after that code, it would add the null return, e.g.:
if #isShown or event.isDefaultPrevented()
return
alert(1)
// compiles to =>
if (this.isShown || event.isDefaultPrevented()) {
return;
}
alert(1);
Whereas in your case above, the function would just exit anyway after the conditional, rendering a null return unnecessary.
You're problem must lie elsewhere... I went to http://coffeescript.org, clicked 'try it', and pasted in your CS code. The JS it generated matches your original JS code.
CoffeeScript error messages often don't actually mean what they say. That's what makes it so much fun... you get be a detective but without having to quit your job as a programmer! Post a larger code block and maybe we can help you with your detective work.