Learn how to a build a cloud-first strategyRegister Now

x
?
Solved

optional variable in javascript

Posted on 2005-04-18
3
Medium Priority
?
578 Views
Last Modified: 2008-03-10
Is there there a way to specify an optional variable in a function call, then set it to a value if nothing is passed through

ie

function test(variable1, variable2 optional=0 )

then used test(1)

variable1 = 1 and variable2 = 0


Thanks
0
Comment
Question by:Sometimes
  • 2
3 Comments
 
LVL 49

Accepted Solution

by:
Roonaan earned 200 total points
ID: 13804756
Each parameter is optional by default, having "null" as an value.
You could therefor test using "==null" to assign another default value.

<script type="text/javascript">
function test(variable1, variable2)
{
 if(variable2 == null) variable2 = 0;
 alert("Var1: " + variable1 + "\nVar2:" + variable2);
}

test(10,11);
test(12);


</script>



-r-
0
 
LVL 2

Author Comment

by:Sometimes
ID: 13804877
but in this case test(,12) doesn't work
0
 
LVL 49

Expert Comment

by:Roonaan
ID: 13804904
No it doesn't. You could however always use: test(null, 12) and add an additional if-clause to the test() function.

Having calls like test(,,,,,12) however sound a bit VB-ish to me.. :^)

-r-
0

Featured Post

What does it mean to be "Always On"?

Is your cloud always on? With an Always On cloud you won't have to worry about downtime for maintenance or software application code updates, ensuring that your bottom line isn't affected.

Question has a verified solution.

If you are experiencing a similar issue, please ask a related question

In Part 1 (http://www.experts-exchange.com/Programming/Languages/Scripting/JavaScript/A_7849-Hex-Maze.html) we covered the hexagonal maze basics -- how the cells are represented in a JavaScript array and how the maze is displayed.  In this part, we'…
Originally, this post was published on Monitis Blog, you can check it here . In business circles, we sometimes hear that today is the “age of the customer.” And so it is. Thanks to the enormous advances over the past few years in consumer techno…
The viewer will learn the basics of jQuery, including how to invoke it on a web page. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery.: (CODE)
The viewer will learn the basics of jQuery including how to code hide show and toggles. Reference your jQuery libraries: (CODE) Include your new external js/jQuery file: (CODE) Write your first lines of code to setup your site for jQuery…
Suggested Courses

810 members asked questions and received personalized solutions in the past 7 days.

Join the community of 500,000 technology professionals and ask your questions.

Join & Ask a Question