Text

Know when it is no longer JSON

Do you ever call your variables that get populated from a JSON string something with “json” in them?

function processData(json) {
    // if (json.accountType == "savings") ...
}

Realize that “JSON” only describes the format of the data you’re fetching through XHR or <script>. It is a string representation of an object. When you’re in the JavaScript domain, and about to process the parsed result of the JSON string, leave “json” behind:

function processData(obj) {
    // if (obj.accountType == "savings") ...
}
Tags: beginner style
Text

Reversing a string

JavaScript doesn’t have a reverse() method for strings but has one for arrays. The trick is to convert a string to an array, reverse the array and combine the array back into a string:

var s = "Hello World!";

var reversed = s.split("").reverse().join("");
// "!dlroW olleH"
Text

Properly clearing properties

If you want to clear a property of an object, simply setting it to undefined won’t always cut it, based on how you will access/test the property later on:

// The setup
var obj = {
    prop: 1
};

// Clear property value
obj.prop = undefined;

The property is still attached to the object as a property and can be enumerated:

for (var key in obj) {
    // Will iterate through "prop"
}

typeof obj.prop == "undefined" // true
obj.hasOwnProperty("prop") // true -- it's still there!

To completely eliminate a property, you need to delete it:

delete obj.prop;

for (var key in obj) {
    // Won't iterate through "prop" anymore
}

typeof obj.prop == "undefined" // true
obj.hasOwnProperty("prop") // false -- it's gone completely!