Upload
ralf-johns
View
223
Download
1
Embed Size (px)
Citation preview
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)) {….}
Number function
• Converts the value into a number.
• It produces NaN if it has a problem.
var number = Number(someValue);
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);
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.
Bizarre Javascript
parseInt(045 + “str", 10); //37
parseInt("045str", 10); //45
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
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
String function
• Converts value to a string
var string = String(someValue);
Boolean
Booleanvar flag = true;
Boolean Type ConversionsFalse True
• false• null• undefined• ""• 0• Number.NaN
•“false”• “0”• ….
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";
Null and Undefined
Value Context in which value is used
String Number Boolean
Undefined value "undefined" NaN false
null "null" 0 false
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"
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.
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)
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.
Arraysvar array = new Array(3); // [undefined, undefined, undefined]
var array = new Array(‘3’); // ["3"]
var array = [3];
sort
var n = [4, 8, 15, 16, 23, 42];
n.sort();
// n is [15, 16, 23, 4, 42, 8]
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.
Deleting ElementsmyArray = ['a', 'b', 'c', 'd'];
delete myArray[1];
// ['a', undefined, 'c', 'd']
myArray.splice(1, 1);
// ['a', 'c', 'd']
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();
WAT
2 == [[[[2]]]]
Unusual operators
A. Addition (+)B. Equality (==) and Identity (===)C. Comparison OperatorsD. The in OperatorE. The instanceof OperatorF. Logical OR (||)G. The delete Operator
• Equal and not equal
• These operators can do type coercion
• It is always better to use === and !==, which do not do 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
Evils of type coercion
Implicit Typecasting
var zero = 0;
/* antipattern */if (zero == false) {
// this block is executed...}
// preferredif (zero === false) {
// not executing because zero is 0, not false}
semicolonvar a = b//blah blah blah(function() {alert(1)})()
With statement
with (obj) {a = b;
}
a = b; a = obj.b; obj.a = b; obj.a = obj.b;
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
Constants
var COLOR_BLUE = "#00F";var COLOR_RED = "#0F0";var COLOR_GREEN = "#F00";var COLOR_ORANGE = "#FF7F00";
Comments
/*When I wrote this, only God and I understood what I was doing
Now, God only knows*/
// Magic. Do not touch.
Example
Variables
JavaScript variables are loosely typed
var myVariable; // undefinedmyVariable = 5; // numbermyVariable += " dollars"; //stringmyVariable = function() { //function
return 3.14159265;}
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.
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.
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();
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();
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
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();
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
}
Namespaces
if (window.myNamespace == null){window.myNamespace = {};
}
window.myNamespace.myFunction = function(/* params*/ ) {/* code here */
};
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)
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( );
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...
}
<script>if (("a" in window) == false) { var a = 1; }alert(a);
</script>
Scope
var foo = 1;
function bar() {if (!foo) {
var foo = 10;}alert(foo);
}
bar();
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
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
eval is evilvar foo = 1;
function myEval(code) {eval(code);
}
function test2() {var foo = 2;myEval("foo = 3");
}
test2();console.log(foo); //3
eval is evil
+ Security Issues
+ eval requires a compile and is therefore slow
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
There are only two kinds of languages: the ones people complain about and the ones nobody uses
Bjarne Stroustrup
QUESTIONS?
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