Skip to content

Instantly share code, notes, and snippets.

@joshfinnie
Last active January 4, 2016 00:49
Show Gist options
  • Save joshfinnie/8543820 to your computer and use it in GitHub Desktop.
Save joshfinnie/8543820 to your computer and use it in GitHub Desktop.

PYTHON

def foo(var="default"):
   print(var)


$ foo()
default

$ foo("not default")
not default

Javascript

function bar(var="default") {
    console.log(var);
}


$ foo()
function bar(var="default")
SyntaxError: Unexpected token =
at Module._compile (module.js:439:25)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
at Function.Module._load (module.js:312:12)
at Module.require (module.js:364:17)
at require (module.js:380:17)
at Object.<anonymous> (/usr/local/src/test.js:4:16)
at Module._compile (module.js:456:26)
at Object.Module._extensions..js (module.js:474:10)
at Module.load (module.js:356:32)
@joshfinnie
Copy link
Author

This is what I am doing... and it seems to be working okay:

function bar(var) {
    var = (typeof var == 'undefined' ? 'default' : var);
    console.log(var);
}

Let me know if anyone has anything better, or if this is dangerously incorrect.

Cheers!

@ryan-roemer
Copy link

@joshfinnie: The general answer is "it depends on what you need" and "it ain't pretty like Python".

When you just need to test for a non-falsy variable, I'd do:

function bar(foo) {
  foo = foo || "default";
  /* ... */
}

If you want to actually check actually arguments (vs. a specified undefined), I'd do:

function bar(foo) {
  foo = arguments.length >= 1 ? foo : "default";
  /* ... */
}

Once you get in to optional parameters and re-ordering, then you have a lot of arguments slicing and inference to do ;)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment