53
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 (! isNaN(number)) { …. }

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,

Embed Size (px)

Citation preview

Page 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,

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 (!isNaN(number)) {….}

Page 2: 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,

Number function

• Converts the value into a number.

• It produces NaN if it has a problem.

var number = Number(someValue);

Page 3: 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,

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

Page 4: 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,

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") == 0parseInt("08", 10) == 8

Octal support has been removed in ECMAScript 5 strict mode.

Page 5: 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,

Bizarre Javascript

parseInt(045 + “str", 10); //37

parseInt("045str", 10); //45

Page 6: 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,

Bizarre Javascript

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

Page 7: 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,

Strings

var simpleString = "test";var stringAsObject = new String("test");

typeof simpleString == "string"typeof stringAsObject == "object“

var nodeTemplate = '<div id="test">Content</div>’;

• 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

Page 8: 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,

String function

• Converts value to a string

var string = String(someValue);

Page 9: 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,

Boolean

Booleanvar flag = true;

Boolean Type ConversionsFalse True

• false• null• undefined• ""• 0• Number.NaN

•“false”• “0”• ….

Page 10: 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,

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

Page 11: 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,

Null and Undefined

Value Context in which value is used

String Number Boolean

Undefined value "undefined" NaN false

null "null" 0 false

Page 12: 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,

typeof operatorType Result

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"

Page 13: 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,

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.

Page 14: 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,

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)

Page 15: 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,

Arrays

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.

Page 16: 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,

Arraysvar array = new Array(3); // [undefined, undefined, undefined]

var array = new Array(‘3’); // ["3"]

var array = [3];

Page 17: 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,

sort

var n = [4, 8, 15, 16, 23, 42];

n.sort();

// n is [15, 16, 23, 4, 42, 8]

Page 18: 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,

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.

Page 19: 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,

Deleting ElementsmyArray = ['a', 'b', 'c', 'd'];

delete myArray[1];

// ['a', undefined, 'c', 'd']

myArray.splice(1, 1);

// ['a', 'c', 'd']

Page 20: 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,

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

Page 21: 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,

WAT

2 == [[[[2]]]]

Page 22: 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,

Unusual operators

A. Addition (+)B. Equality (==) and Identity (===)C. Comparison OperatorsD. The in OperatorE. The instanceof OperatorF. Logical OR (||)G. The delete Operator

Page 23: 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,

• Equal and not equal

• These operators can do type coercion

• It is always better to use === and !==, which do not do type coercion.

== !=

Page 24: 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,

• '' == '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

Page 25: 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,

Implicit Typecasting

var zero = 0;

/* antipattern */if (zero == false) {

// this block is executed...}

// preferredif (zero === false) {

// not executing because zero is 0, not false}

Page 26: 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,

semicolonvar a = b//blah blah blah(function() {alert(1)})()

Page 27: 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,

With statement

with (obj) {a = b;

}

a = b; a = obj.b; obj.a = b; obj.a = obj.b;

Page 28: 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,

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

Page 29: 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,

Constants

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

Page 30: 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,

Comments

/*When I wrote this, only God and I understood what I was doing

Now, God only knows*/

// Magic. Do not touch.

Page 31: 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,

Example

Page 32: 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,

Variables

JavaScript variables are loosely typed

var myVariable; // undefinedmyVariable = 5; // numbermyVariable += " dollars"; //stringmyVariable = function() { //function

return 3.14159265;}

Page 33: 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,

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 }

No Block ScopeOnly functions have scope.

Page 34: 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,

Static (lexical) scopevar 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.

Page 35: 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,

Scope chain

var scope = "global "; // A global variablefunction outer() {

var scope = "local"; // A local variablefunction inner() {

var scope = "nested"; // A nested scope of local variablesdocument.write(scope); // Prints "nested"

}inner();

}outer();

Page 36: 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,

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

Page 37: 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,

Code in global scope

<!DOCTYPE html><html><head> <title>Untitled Page</title><script type="text/javascript" src="script.js"></script>

</head><body><script type="text/javascript">

var a = 5;var b = 2;

function sum(x, y) {return x + y;

}

function mul(x, y) {return x * y;

} </script></body></html>

Index.html

var gloabalVar = 5;function square(x) {

return x * x;}

script.js

Page 38: 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,

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

Page 39: 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,

Globals

// antipatternfunction sum(x, y) {

// implied globalresult = x + y;return result;

}

// antipatternfunction foo() {

var a = b = 0;// ...

}

// preferredfunction foo() {

var a, b;// ...a = b = 0; // both local

}

Page 40: 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,

Namespaces

if (window.myNamespace == null){window.myNamespace = {};

}

window.myNamespace.myFunction = function(/* params*/ ) {/* code here */

};

Page 41: 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,

Hoistingfoo(); // 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)

Page 42: 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,

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

Page 43: 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,

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...

}

Page 44: 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,

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

</script>

Page 45: 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,

Scope

var foo = 1;

function bar() {if (!foo) {

var foo = 10;}alert(foo);

}

bar();

Page 46: 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,

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

Page 47: 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,

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

Page 48: 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,

eval is evilvar foo = 1;

function myEval(code) {eval(code);

}

function test2() {var foo = 2;myEval("foo = 3");

}

test2();console.log(foo); //3

Page 49: 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,

eval is evil

+ Security Issues

+ eval requires a compile and is therefore slow

Page 50: 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,

Embedding scripts in HTMLa) Between a pair of <script> and </script> tags<script type="text/javascript">

alert(“hello world!”);</script>

<script type="text/javascript" src="script.js”></script>

b) From an external file specified by the src attribute of a <script> tag

<button onclick="sayHello();">execute function "sayHello"</button>

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

Page 51: 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,

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

Bjarne Stroustrup

Page 52: 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,

QUESTIONS?

Page 53: 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,

REFERENCES (TODO)

JavaScript: The Definitive Guide, Six Editionby 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