If Else with functions

Asked

Viewed 631 times

3

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

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

I just need to know if functions are loaded into the head work within if-else in scripts within the body, if yes how.

5 answers

10


If you want to call the function, of course it works, but the syntax wouldn’t be this, it would be like this:

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

But if you want to define functions conditionally, then it is not possible, 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() */ };
}

I put in the Github for future reference.

There somewhere you would call salvar().

And I could do something like that too:

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

There’s probably a better way to do what you need but without details you could only suggest this.

  • It worked :) . I’m Bur.. Really. Thank you very much. I will use in an if with confirmation of existence of a given file, if file exists it will ask confirmation if it runs Save(); if not confirmed it returns false, if the document does not exist it runs Save(); also this way it is perfectly working.

5

In fact it is better you create the functions before and when you need to call them, use the if. For example:

function Save(){
    ...
}

function NoSave(){
    ...
}

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

2

You can leave your code smaller also using ternaries:

(a > 1) ? save() : noSave()

2

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

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

0

Short answer: Yes it is possible to use, and there are several forms, being one of them:

if (day == 1){
  (function(){
    alert()
  })()
}

Long answer:

What you want is called anonymity, which is nothing more than a nameless function and which is not accessible after.

Something you can do to not lose this "nameless function" is to save it within a variable,

let awesomeFunc = ()=>{ alert("Olá mundo!") }

and then just calling her

awesomeFunc()

it is possible to use parameters like any other function

   let awesomeFunc = (mensagem)=>{ alert(mensagem) }

    awesomeFunc("Olá mundo lindo")

I recommend reading the links below:

https://www.javascripttutorial.net/javascript-anonymous-functions/ https://www.w3schools.com/js/js_function_definition.asp

Browser other questions tagged

You are not signed in. Login or sign up in order to post.