JavaScript syntax: Difference between revisions

Content deleted Content added
Pepkin88 (talk | contribs)
`null` is not an object
No edit summary
Line 775:
<syntaxhighlight lang="JavaScript">
/**
* To learn JavaScript objects…objects...
*/
var object_1 = {a: 1}; // assign reference of newly created object to object_1
Line 896:
alert([] == false); alert([] ? true : false); // “truthy”, but the comparison uses [].toString()
alert([0] == false); alert([0]? true : false); // [0].toString() == "0"
alert("0" == false); alert("0"? true : false); // "0" → 0 ... (0 == 0) ... 0 ← false
alert([1] == true); alert([1]? true : false); // [1].toString() == "1"
alert("1" == true); alert("1"? true : false); // "1" → 1 ... (1 == 1) ... 1 ← true
alert([2] != true); alert([2]? true : false); // [2].toString() == "2"
alert("2" != true); alert("2"? true : false); // "2" → 2 ... (2 != 1) ... 1 ← true
</syntaxhighlight>
 
Line 976:
A pair of curly brackets <tt>{&nbsp;}</tt> and an enclosed sequence of statements constitute a compound statement, which can be used wherever a statement can be used.
 
===If ... else===
<syntaxhighlight lang="JavaScript">
if (expr) {
Line 1,050:
</syntaxhighlight>
 
===For ... in loop===
The syntax of the JavaScript <code>[[Foreach|for ... in loop]]</code> is as follows:
 
<syntaxhighlight lang="JavaScript">
Line 1,061:
* Iterates through all enumerable properties of an object.
* Iterates through all used indices of array including all user-defined properties of array object, if any. Thus it may be better to use a traditional for loop with a numeric index when iterating over arrays.
* There are differences between the various Web browsers with regard to which properties will be reflected with the for...in loop statement. In theory, this is controlled by an internal state property defined by the ECMAscript standard called "DontEnum", but in practice, each browser returns a slightly different set of properties during introspection. It is useful to test for a given property using {{code|lang=javascript|code=if (some_object.hasOwnProperty(property_name)) { ... }<nowiki />}}. Thus, adding a method to the array prototype with {{code|lang=javascript|code=Array.prototype.newMethod = function() {...}<nowiki />}} may cause <code>for ... in</code> loops to loop over the method's name.
 
===While loop===
Line 1,075:
</syntaxhighlight>
 
===Do ... while loop===
The syntax of the JavaScript <code>[[do while loop|do ... while loop]]</code> is as follows:
 
<syntaxhighlight lang="JavaScript">