JavaScript: Difference between revisions

From Han Wiki
Jump to navigation Jump to search
iwu
 
history
 
(4 intermediate revisions by the same user not shown)
Line 1: Line 1:
== history ==
It was originally written by Brendan Eich in only ten days. Initially called LiveScript.
=== 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
Number("5") * 5; // explicitly convert "5" to number and perform operation
</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">
Math.max(2,4); // 4
Math.max(2,4); // 4
Line 4: Line 39:
confirm("Shall we, then?"); // OK, Cancel
confirm("Shall we, then?"); // OK, Cancel
prompt("Tell me everything you know.","..."); // default "..." OK, Cancel
prompt("Tell me everything you know.","..."); // default "..." OK, Cancel
print("X");
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));
</syntaxhighlight>
</syntaxhighlight>

Latest revision as of 22:07, 19 August 2018

history

It was originally written by Brendan Eich in only ten days. Initially called LiveScript.

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