Hello and welcome to our community! Is this your first visit?
Enjoy an ad free experience by logging in. Not a member yet? Register.

# Thread: Having trouble declaring the function twice

1. ## Having trouble declaring the function twice

I have a quick question. I'm writing a piece of code that will generate if it is an odd number or an even number. I was able to get the output. Now I'm trying to figure out how can I declare the function twice. This is my code:

function f(n)
{
document.write(n);

}

var m=Math.round(1+ Math.random()*100);

if (m%2!==0)
f(m + " is an odd number<br>");
else
f(m + " is an even number<br>");

• No, you cannot have multiple scripts with the same names of functions and/or variables.

If you require a second instance of the same script you must rename all functions and variables to (say) m2 and so on.

Code:
```var m = Math.round(1+ Math.random()*100);
if (m&#37;2 != 0) {
var f = (m + " is an\nodd number");
}
else {
f = (m + " is an\neven number");
}

Not equal to is != not !==
Newline is \n not <br> which is a literal, but newline is not required here.

If at first you don't succeed, redefine success.

• Originally Posted by Philip M

Not equal to is != not !==
Newline is \n not <br> which is a literal, but newline is not required here.
actually not equal is !==, not equivalent is !=.

although all it really needs is the condition changed to if(m&#37;2). no reason to compare to zero here...

OP:
not sure what you mean by "declare the function twice".
you could wrap your loose code in a function, at which point it can be called repeatedly:
Code:
```function f(n){document.write(n);}

function reportEveness(m){
if (m%2){
f(m + " is an odd number<br>");
}else{
f(m + " is an even number<br>");
}
}

// do two different numbers:

var n=Math.round(1+ Math.random()*100);
reportEveness(n);

n=Math.round(1+ Math.random()*100);
reportEveness(n);```

• Thank you kindly I was able to figure out the coding. I meant to say that I would like to run the function twice so that way the results from the random function appears differently rather than the same.

•

#### Posting Permissions

• You may not post new threads
• You may not post replies
• You may not post attachments
• You may not edit your posts
•