JavaScript (jQuery AngularJS) Notes

Better way to compare two floats

When you compare two floats, you’d better not directly compare them. Because in the calculation handled by computer, some minor difference will be introduced into infinities. Try to compare floats if they are equal using:

Math.abs(1 / 3 - (1 - 2 / 3)) < 0.0000001; // true

Convert data to a particular format

toLocaleString() is good for converting a number to formatted string. You do not need to implement any extra methods yourself, JavaScript has done this for you. For example, you have some price to show in a table, you want to display it in USD currency format, just one line:

// Displays "128,000,000" if in U.S. English locale
var price = 128000000; console.log(price.toLocaleString());

Comparing with == and ===

Try to compare with === but not ==. == will convert the variable for comparison, === will only compare when the two comparators are the same type. Using === can avoid some unexpected behavior.

However, there is one exception. NaN === NaN will always return False. The only way to judge if a variable is to use isNaN()

Dynamic Binding

The event handlers can only bind to static elements if you use $(selector).eventHandler(...).

Try to use $(document).on('eventName', handler(){...}? to bind elements that are dynamically generated.

.next(selector)

Will only give you the next sibling, but not finding the next available element for you.

That is, if the next element is not matching selector, it will return empty. Without a selector, it will just give you the next element in DOM tree.

If you want to find anything in all the siblings, use .nextAll(selector) instead.

Leave a Reply

Your email address will not be published. Required fields are marked *