06.07.2017 Views

Mastering JavaScript

Create successful ePaper yourself

Turn your PDF publications into a flip-book with our unique Google optimized e-Paper software.

Chapter 1<br />

You can also omit all three of these expressions and write for loops. One interesting<br />

idiom used frequently is to use for loops with empty statements. The following loop<br />

is used to set all the elements of the array to 100. Notice how there is no body to the<br />

for-loop:<br />

var arr = [10, 20, 30];<br />

// Assign all array values to 100<br />

for (i = 0; i < arr.length; arr[i++] = 100);<br />

console.log(arr);<br />

The empty statement here is just the single that we see after the for loop statement.<br />

The increment factor also modifies the array content. We will discuss arrays later in<br />

the book, but here it's sufficient to see that the array elements are set to the 100 value<br />

within the loop definition itself.<br />

Equality<br />

<strong>JavaScript</strong> offers two modes of equality—strict and loose. Essentially, loose equality<br />

will perform the type conversion when comparing two values, while strict equality<br />

will check the values without any type conversion. A strict equality check is<br />

performed by === while a loose equality check is performed by ==.<br />

ECMAScript 6 also offers the Object.is method to do a strict equality check like ===.<br />

However, Object.is has a special handling for NaN: -0 and +0. When NaN===NaN<br />

and NaN==NaN evaluates to false, Object.is(NaN,NaN) will return true.<br />

Strict equality using ===<br />

Strict equality compares two values without any implicit type conversions. The<br />

following rules apply:<br />

• If the values are of a different type, they are unequal.<br />

• For non-numerical values of the same type, they are equal if their values are<br />

the same.<br />

• For primitive numbers, strict equality works for values. If the values are the<br />

same, === results in true. However, a NaN doesn't equal to any number and<br />

NaN=== would be a false.<br />

[ 25 ]<br />

www.it-ebooks.info

Hooray! Your file is uploaded and ready to be published.

Saved successfully!

Ooh no, something went wrong!