Reputation: 15
Is it required to define parameters in a javascript function? My question is regarding my comchoice
function down below, where I simply use the open and close parentheses without giving any parameters that can be changed.
I listed my full code for the script just for reference
var userChoice = prompt("Do you choose rock, paper or scissors?");
var computerChoice = Math.random();
var compchoice = function ()
{
if (computerChoice <= 0.34)
{
return computerChoice = "Rock";
}
else if(0.35 <= computerChoice <= 0.67)
{
return computerChoice = "Paper";
}
if (0.68 <= computerChoice <= 1)
{
return computerChoice = "Scissors";
}
};
compchoice();
var compare = function (choice1, choice2)
{
if (choice1 === choice2)
{
return alert("The result is a tie!");
}
if (choice1 === "Rock")
{
if (choice2 === "Scissors")
{
return alert("Rock wins!");
}
else if (choice2 === "Paper")
{
return alert("Paper wins!");
}
}
else if (choice1 === "Scissors")
{
if (choice2 === "Rock")
{
return alert("Rock wins!");
}
else if (choice2 === "Paper")
{
return alert("Schissors wins!");
}
}
};
compare(userChoice, computerChoice);
Upvotes: 0
Views: 480
Reputation: 28528
No, it is not necessary to pass parameter, function can be with no parameter. In your case function is accessing the outer variables with closures.
Upvotes: 1
Reputation: 8611
As per the Function Definition Syntax
FunctionExpression :
function Identifieropt ( FormalParameterListopt ) { FunctionBody }(ES5 §13)
In a function expression you can ommit the identifier as well as the parameters.
Hence your code is syntactically valid.
Upvotes: 0
Reputation: 5964
What you can do is something like the following:
function RandomFunction(){
alert( arguments[0] );
console.log( arguments[1] );
}
RandomFunction( 'Hello World', 'Good bye' );
And find the arguments for the function in the "arguments" variable within a function. Thus, no need to declare the argument, but declaring them is always a great way to go.
Also, instead of using traditional arguments, you can pass in an object to be used as an extensible list of objects:
function AnotherFunction( x ){
alert( x.message );
}
AnotherFunction( {message: 'Hello Again, world'} );
Upvotes: 1