JavaScript: Difference between revisions

From Han Wiki
Jump to navigation Jump to search
No edit summary
add more
Line 1: Line 1:
=== examples ===
=== examples ===
things to watch out for in automatic type conversion.
<syntaxhighlight lang="javascript">
"Apollo" + 5; // Apollo5
null + "ify": // nullify
"5" * 5; // 25
"strawberry" * 5; // NaN
NaN == NaN; // false  use isNaN() function instead
</syntaxhighlight>
<syntaxhighlight lang="javascript">
</syntaxhighlight>
automatic type conversion. To disallow automatic type conversion, use === or !== operators.
<syntaxhighlight lang="javascript">
false == 0; // true
"" == 0; // true
"5" == 5; // true
</syntaxhighlight>
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.
<syntaxhighlight lang="javascript">
if (something == undefined) // either undefined or null
</syntaxhighlight>


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

Revision as of 09:27, 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

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));