JavaScript: Difference between revisions

From Han Wiki
Jump to navigation Jump to search
add more
add more
Line 1: Line 1:
=== examples ===
=== examples ===


things to watch out for in automatic type conversion.
Things to watch out for in automatic type conversion.


<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">
Line 10: Line 10:


NaN == NaN; // false  use isNaN() function instead
NaN == NaN; // false  use isNaN() function instead
Number("5") * 5; // explicitly convert "5" to number and perform operation
</syntaxhighlight>
</syntaxhighlight>


Line 15: Line 17:
</syntaxhighlight>
</syntaxhighlight>


automatic type conversion. To disallow automatic type conversion, use === or !== operators.
Automatic type conversion. To disallow automatic type conversion, use === or !== operators.


<syntaxhighlight lang="javascript">
<syntaxhighlight lang="javascript">

Revision as of 10:38, 3 April 2016

examples

Things to watch out for in automatic type conversion.

"Apollo" + 5; // Apollo5
null + "ify": // nullify
"5" * 5; // 25
"strawberry" * 5; // NaN

NaN == NaN; // false  use isNaN() function instead

Number("5") * 5; // explicitly convert "5" to number and perform operation

Automatic type conversion. To disallow automatic type conversion, use === or !== operators.

false == 0; // true

"" == 0; // true

"5" == 5; // true

Check if something is null or defined. if a variable has been defined ("var something") but it hasn't been assigned anything, it returns undefined. All of functions that have no return values also return undefined.

if (something == undefined) // either undefined or null
Math.max(2,4); // 4
Math.min(2,4) + 100; // 102
confirm("Shall we, then?"); // OK, Cancel
prompt("Tell me everything you know.","..."); // default "..." OK, Cancel
print("X"); // print to printer
// 
var theNumber = Number(prompt("Pick a number", ""));
if (!isNaN(theNumber))
   alert("Your number is the square root of " + (theNumber * theNumber));