If else with functions

2

It is possible to use a if-else with functions "function ();" example:

if (a > 1){function Save();}
 else {function NoSave();}

I just need to know if functions loaded in head work within if-else in scripts within body , if yes like.

    
asked by anonymous 26.02.2015 / 14:46

4 answers

9

If you want to call the function, of course it works, but the syntax would not be this, it would look like this:

if (a > 1) {
    Save();
} else {
    NoSave();
}

But if you want to define functions conditionally, there you can not, at least not in this way. You could even define two anonymous functions, like this:

var salvar;
if (a > 1) {
    salvar = function() { //faz alguma coisa que seria o você quer no Save()};
} else {
    salvar = function() { //faz outra coisa ou eventualmente não faz nada, seria o NoSave()};
}

Then somewhere you would call salvar() .

It probably has a better way of doing what you need but without details I could only suggest this.

    
26.02.2015 / 14:52
4

Actually, it's better to create the functions before and when you need to call them, use if. For example:

function Save(){
    ...
}

function NoSave(){
    ...
}

if(a > 1){
    Save();
}else{
    NoSave();
}
    
26.02.2015 / 14:52
2

You can also leave your code smaller by using ternaries:

(a > 1) ? save() : noSave()
    
10.03.2016 / 02:10
1

Yes, you can use it, but you must declare it before and use it as follows within the if:

function T()
{
    if (a > 1)
    {
        Save();
    }else {
        NoSave();
    }
}
    
26.02.2015 / 15:13