530 likes | 947 Views
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 ) { …. }.
E N D
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)) { …. }
varnumber = Number(someValue); • Converts the value into a number. • It produces NaN if it has a problem. Number function
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
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.
parseInt(045 + “str", 10); //37parseInt("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 Bizarre Javascript
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>’;
varstring = String(someValue); String function • Converts value to a string
Boolean varflag = true; Boolean Boolean Type Conversions False True • false • null • undefined • "" • 0 • Number.NaN • “false” • “0” • ….
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";
typeof operator typeof1 == "number"
if (foo !== undefined) //ReferenceError typeoffoo != ‘undefined’ Testing for Undefined Variables • Unless checking whether a variable is defined, • typeofshould be avoided at all costs.
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)
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
vararray = newArray(3); // [undefined, undefined, undefined] vararray = newArray(‘3’); // ["3"] vararray = [3]; Arrays
var n = [4, 8, 15, 16, 23, 42]; n.sort(); // n is [15, 16, 23, 4, 42, 8] sort
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
myArray = ['a', 'b', 'c', 'd']; delete myArray[1]; // ['a', undefined, 'c', 'd'] myArray.splice(1, 1); // ['a', 'c', 'd'] Deleting Elements
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
2 == [[[[2]]]] WAT
Addition (+) Equality (==) and Identity (===) Comparison Operators The in Operator The instanceof Operator Logical OR (||) The delete Operator Unusual operators
== != • Equal and not equal • These operators can do type coercion • It is always better to use === and !==, which do not do type coercion.
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
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 }
semicolon var a = b //blah blahblah (function() {alert(1)})()
with (obj) { a = b; } With statement a = b; a = obj.b; obj.a = b; obj.a = obj.b;
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
var COLOR_BLUE = "#00F"; var COLOR_RED = "#0F0"; var COLOR_GREEN = "#F00"; var COLOR_ORANGE = "#FF7F00"; Constants
/* • When I wrote this, only God and I understood what I was doing • Now, God only knows • */ Comments //Magic. Do not touch.
JavaScript variables are loosely typed varmyVariable; // undefined myVariable = 5; // number myVariable += " dollars"; //string myVariable = function() { //function return3.14159265; } Variables
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
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.
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
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();
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; }
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
// 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
if (window.myNamespace == null){ window.myNamespace = {}; } window.myNamespace.myFunction= function(/* params*/ ) { /* code here */ }; Namespaces
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)
varscope = "global "; functionf( ) { alert(scope); varscope = "local"; alert(scope); } f( ); Hoisting varscope = "global "; functionf( ) { varscope; alert(scope); scope = "local"; alert(scope); } f( );
/* 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
<script> • if (("a" in window) == false) { • var a = 1; • } • alert(a); • </script>
var foo = 1; function bar() { if(!foo) { varfoo = 10; } alert(foo); } bar(); Scope
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
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
var 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 + evalrequires a compile and is therefore slow eval is evil
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”);