r/ProgrammerHumor • • Dec 31 '14

How to add two numbers in JavaScript

1.7k Upvotes

270 comments sorted by

View all comments

Show parent comments

3

u/the_omega99 Dec 31 '14

With JS, you can have default variables by simply checking if the variable is unset and setting it to an appropriate default if so (and presumably that appropriate default is any "falsey" value).

Eg,

function foo(x) {
    if(x === undefined) x = "default";
    console.log(x);
}

foo() // prints "default"
foo(5) // prints "5"

A little different from how other languages handle default variables, but really quite useful. If you have a callback that supplies arguments but you don't need them, you can exclude them entirely, making your code more readable (most statically typed languages will complain here).

1

u/Daniel15 Dec 31 '14

Lots of languages support default values for arguments (I know C# and PHP both do) and JavaScript is getting first class support for it with ES6: http://dmitrysoshnikov.com/ecmascript/es6-notes-default-values-of-parameters/