0

How do I tell Javascript to use zero as a variable if the passed variable if empty? In PHP I can use the following.

<?php
   function test($var=0){
      echo $var;
   }
?>

So it would set $var to 0 if the passed variable was empty. I can't seem to figure this out in Javascript.

Thanks

4 Answers 4

4

If you call a method without providing a value for one (or more) of the arguments, those arguments will be undefined.

Thus within the method you can test whether the variable is defined, and if not assign it a default value:

function test(arg) {
    if (typeof(arg) === 'undefined') {
        arg = "default"; // or whatever default value you want
    };

    // Rest of method
}

It's not very elegant, but Javascript doesn't have a nice native default-arguments syntax.

Sign up to request clarification or add additional context in comments.

3 Comments

Works great. It's a shame it's not very elegant as you put it, but it does the job. Thanks!
var is a reserved keyword! your example will generate a syntax error.
Very true Salman - I was mirroring the PHP example in the question but that's not really an excuse for illegal syntax! I'll update it now, thanks.
2

You can use the or operator to do this a bit shorter;

function myFunc(var)
{
 var = var || 0;
}

1 Comment

What if var is the boolean value false? Or an empty string? Or the integer 0? Or any other "truthy" value provided by the caller?
2

It strongly depends on what empty means for you and what values the argument is allowed to have.

An often used shortcut is

param = param || 0;

This will set param to 0 whenever param evaluates to false.

Comments

1

This should work:

function myFunc(var) {
   if (null == var)
      var = 0; 
}

1 Comment

Strictly that only works because of type coercion, which isn't entirely what's required. var is not null if it's unprovided, it's undefined. Your code here would assign the default value even if the caller passed in an explicit value of null, which is not as I understand the requirement.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.