Use same if statements in multiple functions

Greetings all,

quick question. I have a series of the same if statements which I’m using in multiple functions. To avoid repetition I thought of putting these statements into their own function and then calling the function in the other functions.

This is just a simple example, but nothing is happening. What am I doing wrong?

Thank you for any help!

function notify() {
if (a == "one") {
var c = "one";
}
if (b == "two") {
var c = "two";
}  
}

$(function() {
notify();
});

$(function() {
notify();
});

What are these a, b and c variables? Where are they coming from?
Also, all you’re doing is setting variables, you won’t see any direct effect if this.

I’d start by rewriting the function as:

function notify(a,b) {
var c;
if (a === 'one') {
   c = 'one';
}
if (b === 'two') {
   c = 'two';
}
return c;
}

Then you are not relying on global variables (which are almost never required in JavaScript) for passing values to and from the function.

You can then call the code (assuming that the variables in the calling function are a, b, and c using:

c = notify(a,b);

1 Like

Hi ScallioXTX and felgall,

thank you for replying.

Basically just checking and assigning values.

Thanks felgall, that solved the problem.

I appreciate your help and hope the two of you are having a good weekend. Cheers.