1 / 53

NaN (Not a Number)

Result of erroneous operations. Any arithmetic operation with NaN as an input will have NaN as a result. NaN is not equal to anything, including NaN . Use IsNaN () to determine whether a value is NaN. NaN (Not a Number). v ar number = "string" / 2; If (number != NaN ) { …. }.

Télécharger la présentation

NaN (Not a Number)

An Image/Link below is provided (as is) to download presentation Download Policy: Content on the Website is provided to you AS IS for your information and personal use and may not be sold / licensed / shared on other websites without getting consent from its author. Content is provided to you AS IS for your information and personal use only. Download presentation by click this link. While downloading, if for some reason you are not able to download a presentation, the publisher may have deleted the file from their server. During download, if you can't get a presentation, the file might be deleted by the publisher.

E N D

Presentation Transcript


  1. Result of erroneous operations. Any arithmetic operation with NaN as an input will have NaN as a result. NaN is not equal to anything, including NaN. Use IsNaN() to determine whether a value is NaN NaN (Not a Number) var number = "string" / 2; If (number != NaN) { …. } var number = "string" / 2; If (!isNaN(number)) { …. }

  2. varnumber = Number(someValue); • Converts the value into a number. • It produces NaN if it has a problem. Number function

  3. varnumber = parseInt(someValue, 10); • Converts the value into a number. • It stops at the first non-digit character. • The radix (10) should be required. parseInt function

  4. parseInt("08") == 0 parseInt("08", 10) == 8 parseInt function • If you omit radix, following the rules : • If the string begins with "0x", the radix is 16 • If the string begins with "0", the radix is 8 • If the string begins with any other value, the radix is 10 Octal support has been removed in ECMAScript 5 strict mode.

  5. parseInt(045 + “str", 10); //37parseInt("045str", 10); //45 Bizarre Javascript

  6. 2.toString(); // raises SyntaxError(identifier starts immediately after numeric // literal) Fix: 2..toString(); // the second point is correctly recognized2 .toString(); // note the space left to the dot(2).toString(); // 2 is evaluated first Bizarre Javascript

  7. Sequence of 0 or more 16-bit characters • No separate character type • Strings are immutable • Similar strings are equal ( == ) • String literals can use single or double quotes Strings varsimpleString = "test"; varstringAsObject = newString("test"); typeofsimpleString == "string" typeofstringAsObject == "object“ varnodeTemplate = '<div id="test">Content</div>’;

  8. varstring = String(someValue); String function • Converts value to a string

  9. Boolean varflag = true; Boolean Boolean Type Conversions False True • false • null • undefined • "" • 0 • Number.NaN • “false” • “0” • ….

  10. varbooleanVariable= Boolean(someValue); • returns true if value is truthy • returns false if value is falsy • Similar to !! prefix operator Boolean function varbooleanVariable= Boolean("false"); varbooleanVariable= !!"false";

  11. Null and Undefined

  12. typeof operator typeof1 == "number"

  13. if (foo !== undefined) //ReferenceError typeoffoo != ‘undefined’ Testing for Undefined Variables • Unless checking whether a variable is defined,  • typeofshould be avoided at all costs.

  14. Primitive types are manipulated by value. Object types are manipulated by sharing. Strategy of passing arguments to function • function x(t){ • t.a = 5; • t = {}; • } • varobj = {}; • x(obj) • console.log(obj)

  15. Array inherits from Object. • Indexes are converted to strings and used as names for retrieving values. • Arrayshave a special length member. Arrays vararray = newArray(1, 2, 3); vararray = [1,2,3]; vararray = [1, "234234", true, function() { alert("hello!"); } ]; array.length

  16. vararray = newArray(3); // [undefined, undefined, undefined] vararray = newArray(‘3’); // ["3"] vararray = [3]; Arrays

  17. var n = [4, 8, 15, 16, 23, 42]; n.sort(); // n is [15, 16, 23, 4, 42, 8] sort

  18. delete array[number] Removes the element, but leaves a hole in the numbering. array.splice(number, 1) Removes the element and renumbers all the following elements. Deleting Elements

  19. myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // ['a', undefined, 'c', 'd'] myArray.splice(1, 1); // ['a', 'c', 'd'] Deleting Elements

  20. vararrayAsString = array.join("separator"); array.reverse(); array.sort(/* options: comparison function */);//important varnewArray = array.concat("array"); varsubarray = array.slice(“startIndex”,”lastIndex”); array.splice(“startIndex”,”itemsToRemove”,/*new items*/); varnewArrayLength = array.push(“value”); varremovedValue= array.pop(); varnewArrayLength = array.unshift(“value”) ; varremovedValue= array.shift(); Array methods

  21. 2 == [[[[2]]]] WAT

  22. Addition (+) Equality (==) and Identity (===) Comparison Operators The in Operator The instanceof Operator Logical OR (||) The delete Operator Unusual operators

  23. == != • Equal and not equal • These operators can do type coercion • It is always better to use === and !==, which do not do type coercion.

  24. Evils of type coercion • '' == '0' // false • 0 == '' // true • 0 == '0' // true • false == 'false' // false • false == '0' // true • false == undefined // false • false == null // false • null == undefined // true • ‘ \t\r\n ' == 0 // true

  25. Implicit Typecasting var zero = 0; /* antipattern */ if (zero == false) { // this block is executed... } // preferred if(zero === false) { // not executing because zero is 0, not false }

  26. semicolon var a = b //blah blahblah (function() {alert(1)})()

  27. with (obj) { a = b; } With statement a = b; a = obj.b; obj.a = b; obj.a = obj.b;

  28. Starts with a letter or _ or $ • Followed by zero or more letters, digits, _ or $ • By convention, all variables, parameters, members, and function names start with lower case • Except for constructors which start with upper case Identifiers

  29. var COLOR_BLUE = "#00F"; var COLOR_RED = "#0F0"; var COLOR_GREEN = "#F00"; var COLOR_ORANGE = "#FF7F00"; Constants

  30. /* • When I wrote this, only God and I understood what I was doing • Now, God only knows • */ Comments //Magic. Do not touch.

  31. Example

  32. JavaScript variables are loosely typed varmyVariable; // undefined myVariable = 5; // number myVariable += " dollars"; //string myVariable = function() { //function return3.14159265; } Variables

  33. No Block Scope Only functions have scope. functiontest(o) { vari = 0; // i is defined throughout function if (typeofo == "object") { varj = 0; // j is defined everywhere, not just block for(vark=0; k < 10; k++) { // k is defined everywhere, not just loop document.write(k); } document.write(k); // k is still defined: prints 10 } document.write(j); // j is defined, but may not be initialized } Scope

  34. var z = 10; • function foo() { • alert(z); • } • foo(); • (function () { • var z = 20; • foo(); • })(); Static (lexical) scope The word “static” relates to ability to determine the scope of an identifier during the parsing stage of a program.

  35. varscope = "global "; // A global variable functionouter() { varscope = "local"; // A local variable functioninner() { varscope = "nested"; // A nested scope of local variables document.write(scope); // Prints "nested" } inner(); } outer(); Scope chain

  36. function X() { vara = 3, b = 5; function foo () { varb = 7, c = 11; a += b + c; }; foo(); alert("a = " + a + "; b = " + b); } X(); varx = function(){ alert(x.toString()); } x();

  37. Index.html • <!DOCTYPEhtml> • <html> • <head> • <title>Untitled Page</title> • <scripttype="text/javascript" src="script.js"></script> • </head> • <body> • <scripttype="text/javascript"> • var a = 5; • var b = 2; • function sum(x, y) { • returnx + y; • } • functionmul(x, y) { • returnx * y; • } • </script> • </body> • </html> Code in global scope script.js vargloabalVar = 5; function square(x) { returnx * x; }

  38. Every variable is global unless it's in a function and is declared with var Global namespace window.globalVariable = “global”; function x(){ globalVariable2 = “global2”; } x(); Global variables are evil

  39. // antipattern • functionsum(x, y) { • // implied global • result = x + y; • return result; • } • // antipattern • function foo() { • var a = b = 0; • // ... • } • // preferred • function foo() { • var a, b; • // ... • a = b = 0; // both local • } Globals

  40. if (window.myNamespace == null){ window.myNamespace = {}; } window.myNamespace.myFunction= function(/* params*/ ) { /* code here */ }; Namespaces

  41. foo(); // undefined ("foo" and "bar" exist) functionfoo() { alert(bar); } var bar; Hoisting function foo() { alert(bar); } varbar; foo(); // undefined (now we see that they exist)

  42. varscope = "global "; functionf( ) { alert(scope); varscope = "local"; alert(scope); } f( ); Hoisting varscope = "global "; functionf( ) { varscope; alert(scope); scope = "local"; alert(scope); } f( );

  43. /* Benefits: • * 1. Provides a single place to look for all the local variables needed by the function • * 2. Prevents logical errors when a variable is used before it's defined • * 3. Helps you remember to declare variables and therefore minimize globals • * 4. Is less code (to type and to transfer over the wire) • */ • functionfunc() { • var a = 1, • b = 2, • sum = a + b, • myobject = {}, • i, • j; • // function body... • } • functionupdateElement() { • var el = document.getElementById("result"), • style = el.style; • // do something with el and style... • } Single varPattern

  44. <script> • if (("a" in window) == false) { • var a = 1; • } • alert(a); • </script>

  45. var foo = 1; function bar() { if(!foo) { varfoo = 10; } alert(foo); } bar(); Scope

  46. Javascript can compile text to an executable code: eval() - compile a string as JavaScript. new Function() - compile a function. setTimeout, setInterval - can both take a string as their first argument Code generation

  47. The eval function will execute a string of JavaScript code in the current scope var foo = 1; function test1() { var foo = 2; eval("foo = 3"); } test1(); console.log(foo); // 1 eval is evil

  48. var foo = 1; function myEval(code) { eval(code); } function test2() { var foo = 2; myEval("foo = 3"); } test2(); console.log(foo); //3 eval is evil

  49. + Security Issues + evalrequires a compile and is therefore slow eval is evil

  50. a) Between a pair of <script> and </script> tags <script type="text/javascript"> alert(“hello world!”); </script> Embedding scripts in HTML b) From an external file specified by the src attribute of a <script> tag <script type="text/javascript" src="script.js”></script> c) In an event handler, specified as the value of an HTML attribute such as onclick or onmouseover <button onclick="sayHello();">execute function "sayHello"</button> d) In a URL, uses the special javascript: protocol javascript:alert(“Hello world”);

More Related