Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

anonymous function doesn't always return a value

I've got JavaScript code like this =>

(function(){
    document.getElementById("element").onclick = function(){
        var r = confirm("Are you sure ?");
        if (r){
            return true;
        } else {
            return false;
        }
    }
})();

this script works, but just gives me notification about Strict Warning that anonymous function doesn't always return a value

I'm interested in what that means, how can I prevent this and will it provoke any problem ? Please any ideas ? thanks :)

like image 547
nanobash Avatar asked Jul 27 '12 22:07

nanobash


Video Answer


2 Answers

It's not because of the anonymous function, it's because the else with that return is redundant. You don't need it since return exits the function, if the if statement is not true then the default return will execute.

(function(){
    document.getElementById("element").onclick = function(){
        var r = confirm("Are you sure ?");
        if (r){
            return true;
        }
        return false;
    }
})();

Edit:

As nebulae said this can be done even shorter:

(function(){
    document.getElementById("element").onclick = function(){
        return confirm("Are you sure ?");
    }
})();
like image 105
elclanrs Avatar answered Sep 24 '22 21:09

elclanrs


Actually the strict warning you are getting because of strict mode enabled in you script but if "use strict" is not being used in your script then I think, as you said in comment that you are using Komodo IDE and most probably you have installed Firefox Extension for Debugging which is required to support the browser-side component of JavaScript debugging.

If so then it has some settings that you can eneble or disable. To disable strict mode warnings just go to Edit Menu > Preferences > Javascript (from category) and uncheck the Enable Strict Warning Messages, that's it. But using strict mode is a good programming practice. Below is a screenshot to help you

enter image description here

like image 39
The Alpha Avatar answered Sep 24 '22 21:09

The Alpha