Skip to content

Instantly share code, notes, and snippets.

@gigafied
Created February 15, 2012 02:27
Show Gist options
  • Save gigafied/1832647 to your computer and use it in GitHub Desktop.
Save gigafied/1832647 to your computer and use it in GitHub Desktop.
== use cases
function createBox1 (width, height, x, y) {
x = x || 100;
y = y || 200;
return {width: width, height: height, x: x, y: y};
}
function createBox2 (width, height, x, y) {
x = x == null ? 100 : x;
y = y == null ? 200 : y;
return {width: width, height: height, x: x, y: y};
}
function createBox3 (width, height, x, y) {
x = x === null ? 100 : x;
y = y === null ? 200 : y;
return {width: width, height: height, x: x, y: y};
}
function createBox4 (width, height, x, y) {
x = (x === null || typeof x === "undefined") ? 100 : x;
y = (y === null || typeof y === "undefined") ? 200 : y;
return {width: width, height: height, x: x, y: y};
}
console.log(createBox1(100,100)); // { width: 100, height: 100, x: 100, y: 200 }. OK
console.log(createBox2(100,100)); // { width: 100, height: 100, x: 100, y: 200 }. OK
console.log(createBox3(100,100)); // { width: 100, height: 100, x: undefined, y: undefined }. FAIL
console.log(createBox4(100,100)); // { width: 100, height: 100, x: 100, y: 200 }. OK
console.log(createBox1(100,100, 0, 0)); // { width: 100, height: 100, x: 100, y: 200 }. FAIL
console.log(createBox2(100,100, 0, 0)); // { width: 100, height: 100, x: 0, y: 0 }. OK
console.log(createBox3(100,100, 0, 0)); // { width: 100, height: 100, x: 0, y: 0 }. OK
console.log(createBox4(100,100, 0, 0)); // { width: 100, height: 100, x: 0, y: 0 }. OK
@gigafied
Copy link
Author

As you can see createBox2 and createBox4 are the only functions that behave as expected, createBox2 is less verbose and more legible, this is why I advocate not strictly enforcing "==="

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