Presentation is loading. Please wait.

Presentation is loading. Please wait.

NaN (Not a Number) 1.Result of erroneous operations. 2.Any arithmetic operation with NaN as an input will have NaN as a result. 3.NaN is not equal to anything,

Similar presentations


Presentation on theme: "NaN (Not a Number) 1.Result of erroneous operations. 2.Any arithmetic operation with NaN as an input will have NaN as a result. 3.NaN is not equal to anything,"— Presentation transcript:

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

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

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

4 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 parseInt("08") == 0 parseInt("08", 10) == 8 parseInt("08") == 0 parseInt("08", 10) == 8 Octal support has been removed in ECMAScript 5 strict mode.

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

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

7 Strings var simpleString = "test"; var stringAsObject = new String("test"); typeof simpleString == "string" typeof stringAsObject == "object“ var nodeTemplate = ' Content ’; var simpleString = "test"; var stringAsObject = new String("test"); typeof simpleString == "string" typeof stringAsObject == "object“ var nodeTemplate = ' Content ’; 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

8 String function Converts value to a string var string = String(someValue);

9 Boolean var flag = true; Boolean Type Conversions FalseTrue false null undefined "" 0 Number.NaN “false” “0” ….

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

11 Null and Undefined ValueContext in which value is used StringNumberBoolean Undefined value"undefined"NaNfalse null"null"0false

12 typeof operator TypeResult undefined"undefined" null"object" true"boolean" new Boolean(true)"object" 5"number" new Number(5)"object" “foo”"string" new String(“foo”)"object" [1, 2, 3]"object" function foo() {}"function" Any other object"object" typeof 1 == "number"

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

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

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

16 Arrays var array = new Array(3); // [undefined, undefined, undefined] var array = new Array(‘3’); // ["3"] var array = [3]; var array = new Array(3); // [undefined, undefined, undefined] var array = new Array(‘3’); // ["3"] var array = [3];

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

18 Deleting Elements 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.

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

20 Array methods 1.var arrayAsString = array.join("separator"); 2.array.reverse(); 3.array.sort(/* options: comparison function */);//important 4.var newArray = array.concat("array"); 5.var subarray = array.slice(“startIndex”,”lastIndex”); 6.array.splice(“startIndex”,”itemsToRemove”,/*new items*/); 7.var newArrayLength = array.push(“value”); 8.var removedValue= array.pop(); 9.var newArrayLength = array.unshift(“value”) ; 10.var removedValue= array.shift(); 1.var arrayAsString = array.join("separator"); 2.array.reverse(); 3.array.sort(/* options: comparison function */);//important 4.var newArray = array.concat("array"); 5.var subarray = array.slice(“startIndex”,”lastIndex”); 6.array.splice(“startIndex”,”itemsToRemove”,/*new items*/); 7.var newArrayLength = array.push(“value”); 8.var removedValue= array.pop(); 9.var newArrayLength = array.unshift(“value”) ; 10.var removedValue= array.shift();

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

22 Unusual operators A.Addition (+) B.Equality (==) and Identity (===) C.Comparison Operators D.The in Operator E.The instanceof Operator F.Logical OR (||) G.The delete Operator

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 '' == '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 Evils of type coercion

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 } 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 blah blah (function() {alert(1)})() var a = b //blah blah blah (function() {alert(1)})()

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

28 Identifiers 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

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

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

31 Example

32 Variables JavaScript variables are loosely typed var myVariable; // undefined myVariable = 5; // number myVariable += " dollars"; //string myVariable = function() { //function return 3.14159265; } var myVariable; // undefined myVariable = 5; // number myVariable += " dollars"; //string myVariable = function() { //function return 3.14159265; }

33 Scope function test(o) { var i = 0; // i is defined throughout function if (typeof o == "object") { var j = 0; // j is defined everywhere, not just block for(var k=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 } function test(o) { var i = 0; // i is defined throughout function if (typeof o == "object") { var j = 0; // j is defined everywhere, not just block for(var k=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 } No Block Scope Only functions have scope.

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

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

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

37 Code in global scope Untitled Page var a = 5; var b = 2; function sum(x, y) { return x + y; } function mul(x, y) { return x * y; } Untitled Page var a = 5; var b = 2; function sum(x, y) { return x + y; } function mul(x, y) { return x * y; } Index.html var gloabalVar = 5; function square(x) { return x * x; } var gloabalVar = 5; function square(x) { return x * x; } script.js

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

39 Globals // antipattern function sum(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 } // antipattern function sum(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 }

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

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

42 Hoisting var scope = "global "; function f( ) { alert(scope); var scope = "local"; alert(scope); } f( ); var scope = "global "; function f( ) { alert(scope); var scope = "local"; alert(scope); } f( ); var scope = "global "; function f( ) { var scope; alert(scope); scope = "local"; alert(scope); } f( ); var scope = "global "; function f( ) { var scope; alert(scope); scope = "local"; alert(scope); } f( );

43 Single var Pattern /* 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) */ function func() { var a = 1, b = 2, sum = a + b, myobject = {}, i, j; // function body... } function updateElement() { var el = document.getElementById("result"), style = el.style; // do something with el and style... } /* 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) */ function func() { var a = 1, b = 2, sum = a + b, myobject = {}, i, j; // function body... } function updateElement() { var el = document.getElementById("result"), style = el.style; // do something with el and style... }

44 if (("a" in window) == false) { var a = 1; } alert(a);

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

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

47 eval is evil 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 var foo = 1; function test1() { var foo = 2; eval("foo = 3"); } test1(); console.log(foo); // 1

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

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

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

51 There are only two kinds of languages: the ones people complain about and the ones nobody uses Bjarne Stroustrup

52

53 REFERENCES (TODO) JavaScript: The Definitive Guide, Six Edition by David Flanagan http://javascript.crockford.com/ http://developer.yahoo.com/yui/theater/ http://dmitrysoshnikov.com http://javascript.ru http://www.w3schools.com http://google-styleguide.googlecode.com/svn/trunk/javascriptguide.xml


Download ppt "NaN (Not a Number) 1.Result of erroneous operations. 2.Any arithmetic operation with NaN as an input will have NaN as a result. 3.NaN is not equal to anything,"

Similar presentations


Ads by Google