Created
February 15, 2012 02:27
-
-
Save gigafied/1832647 to your computer and use it in GitHub Desktop.
== use cases
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
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 |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
As you can see
createBox2
andcreateBox4
are the only functions that behave as expected,createBox2
is less verbose and more legible, this is why I advocate not strictly enforcing "==="