[ECMAScript 5]
DOM - Document Object Model
DOM Level 1 consists of
The Boolean Type
parseFloat(..)
var num = parseFloat( "1234blue" ) ; // 1234 int
DOM Level 1 consists of
- DOM Core - Map structure of XML Document to allow easy access & manipulation of any part of document.
- DOM HTML - Extends DOM Core by adding HTML specific elements
DOM is not JavaScript specific.
DOM Level 2 has - Added support for mouse & UI ranges, Traversals, CSS.
New modules added into DOM2 are
- DOM Views - Describes interfaces to keep track of various views of a document.
- DOM Events - Describes interfaces for events and event handling.
- DOM Style - Describes interfaces to deal with CSS-based styling elements.
- DOM Traversal & Range - Describes interfaces to traverse & manipulate a document tree.
DOM Level 3 extends DOM with introduction of new modules LOAD & SAVE & methods to validate a document.
BOM - Browser Object Model
Allowed access & modification of browser window. BOM deals with browser window & frames but generally any browser specific extension is considered to be part of BOM JavaScript. Some of these extensions are
- Capability to pop-up windows
- Capability to move, resize & close browser window.
- Navigator object which provides detailed information about the browser.
- Location object - which gives detailed information about the page loaded in the browser.
- Screen object - which gives info about users screen resolution.
- Support for cookies.
- Custom objects - ActiveXObject & XMLHttpRequest.
Javascript in HTML
Primary method of inserting JavaScript into HTML is via <script> element.
Two ways to insert the script element.
- Embed JS code with the script element into the page.
- Include JavaScript from external file.
<script type="text/javascript" src="http://www.somewhere.com/theFile.js">
The src attribute can be set to external domain just like the <img> tag's src attribute. (this is a security concern as a malicious JS can be injected (by replacing the JS contents).
The JavaScript code between the <script> tags is interpreted from top to bottom.
Traditionally <script> tag was placed in the <head> of a document. This caused the page to slow when loading. Now <script> is placed within <body> after page content.
Setting the value of defer attribute can cause the page to load scripts after the entire page has been parsed (only for external files).
async attribute provides different loading of scripts.
<noscript> - can contain any HTML elements but <script>. This is used for browsers not supporting JS or disabled JS. The content within <noscript> is displayed when JS is not supported or switched off.
Chapter 2 - Language basics
JavaScript is case sensitive.
Identifiers
- must start with a letter OR _ OR $
- all other characters can be letter OR _ OR $ OR numbers.
- reserved words cant be used as identifiers
- attempting to use a keyword as identifier will cause as "Identifier Expected" error.
Comments
- // OR /* .... *..... */
StrictMode
ECMAScript-5 introduced. strict mode is a different parsing model for JS which throws errors for unsafe activities.
function something(){
"use strict"
}
Statements
- ends with a semi colon. If not provided the parser determines the end of the line.
- Blocks defined by {... } for multiple statements.
Variables
- ES (JS) variables are loosely typed. A variable can hold any type of data.
- using var to define a variable makes it local to the scope in which it is defined.
var message; // if not initialised its value is "undefined"
Data Type
- FIVE data types are defined in JavaScript (primitive)
- Undefined
- Null
- Boolean
- Number
- String
Complex - Object - Unordered list of name-value pairs.
typeof operator (is not a function) - Returns string based on type of data referenced by the variable.
"undefined"
"string" - typeof "a string" ;// "string"
"boolean"
"number" - typeof 75; // "number"
"object" - for object & null
"function"
var message;
// var age ( not defined)
alert( message ) // "undefined"
alert( age ) // "error"
alert( typeof message ) // "undefined"
alert( typeof age ) // "undefined"
var car = null;
alert( typeof car); // "object"
alert ( null == undefined ); // true
The Boolean Type
Only 2 literal values true & false and is case sensitive.
All types of values have Boolean equivalents. This is determined using the Boolean( ... ) function.
DataType | Values converted to true | Values converted to false
Boolean | true | false
String | non empty string | ""
Number | non zero number | 0, NaN
Object | Any Object | null
Undefined | n/a | undefined
var float1 = 0.1; // valid
var float2 = 7.5; // valid
var float3 = .7 ; //valid but not recommended
var floatAsInt1 = 1. ; // interpreted / converted to int
DataType | Values converted to true | Values converted to false
Boolean | true | false
String | non empty string | ""
Number | non zero number | 0, NaN
Object | Any Object | null
Undefined | n/a | undefined
The Number Type
Uses IEEE-754 format for Integer & Floating
Several different number literal formats are supported.
var anInteger = 99; // integer
octal
Octal base 8 numbers should start with '0'
var octal1 = 070 ; // 56
To define a floating point include a decimal and at least one number after it.Several different number literal formats are supported.
var anInteger = 99; // integer
octal
Octal base 8 numbers should start with '0'
var octal1 = 070 ; // 56
var octal2 = 079 ; // not an octal = 79
var octal3 = 08 ; // not octal = 8
octals are invalid in strict mode.
hexadecimal = 0x..
var hex1 = 0xA // = 10
var hex2 = 0x1f // = 31
floating point
octals are invalid in strict mode.
hexadecimal = 0x..
var hex1 = 0xA // = 10
var hex2 = 0x1f // = 31
floating point
var float1 = 0.1; // valid
var float2 = 7.5; // valid
var float3 = .7 ; //valid but not recommended
var floatAsInt1 = 1. ; // interpreted / converted to int
var floatAsInt2 = 10.0 ; // interpreted / converted to int
For large floating point numbers use e-notation.
var floatLarge = 3.126e7 ; // 31260000
var floatSmall = 0.00000000003; // 3e-10
Range Number.MIN_VALUE = 5e-324 Number.MAX_VALUE = 1.7e+308
outside this range we have Infinity & -Infinity
isFinite( theNumber ) - id to check a number is within the above range.
NaN = Not a Number
alert( Nan == Nan ); //false
alert( isNaN(NaN)) ; //true
alert( isNaN( 10 )) ; //false
alert( isNaN("10")) ; //false
alert( isNaN("blue")) ; //true
alert( isNaN(true)) ; //false - get converted to 1
Number Conversions
Number(..) can be used on any datatype.
Number(null) => 0
Number(undefined) => NaN
Number("0xF") => equivalent Integer
Number("") => 0
parseInt(..)
First non-white character should be "+ / - / number" otherwise it returns NaN.
var num = parseInt ( "1234blue" ) ; // 1234
var num = parseInt ( "1234blue" ) ; // 1234
var num = parseInt ( "" ) ; // NaN
var num = parseInt ( "0xA" ) ; // 10 Hexadecimal
var num = parseInt ( "22.5" ) ; // 22
var num = parseInt ( "70" ) ; // 70
Use of radix to define base of string
Use of radix to define base of string
var num = parseInt ( "AF", 16 ) ; // 1234
var num = parseInt ( "AF" ) ; // Nan
parseFloat(..)
var num = parseFloat( "1234blue" ) ; // 1234 int
var num = parseFloat( "0xA" ) ; // 0 int
var num = parseFloat( "22.5" ) ; // 22.5
var num = parseFloat( "22.34.5" ) ; // 22.34
var num = parseFloat( "0908.5" ) ; // 908.5
var num = parseFloat( "3.125e7" ) ; // 31250000
The String Type
Defined using " or '. Both are equivalent.
Strings are immutable.
toString() is available on every value. Accepts radix as parameter for numbers.
Not available on null & undefined.
If the value can be null / undefined use the cast function String()
String (null) => "null"
String (undefined) => "undefined"
The Object Type
Object start as non-specific group of DATA & FUNCTIONALITY.
The String Type
Defined using " or '. Both are equivalent.
Strings are immutable.
toString() is available on every value. Accepts radix as parameter for numbers.
- Number
- Boolean
- Object
- String
Not available on null & undefined.
If the value can be null / undefined use the cast function String()
String (null) => "null"
String (undefined) => "undefined"
The Object Type
Object start as non-specific group of DATA & FUNCTIONALITY.
Objects are created using the new operator followed by the name of the Object Type to create.
var o = new Object();
parenthesis is not mandatory if there are no parameters/arguments.
Object Type is base in ECMAScript from which all other objects are derived.
Each object instance has following properties & methods.
Unary Plus and Minus
Bitwise Operators
var o = new Object();
parenthesis is not mandatory if there are no parameters/arguments.
Object Type is base in ECMAScript from which all other objects are derived.
Each object instance has following properties & methods.
- Constructor - The function that was used to create the object.
- hasOwnProperty( "pName" ) - Indicates if the given property exists on the object instance (not the Prototype (class))
- isPrototypeOf (Object) - If the object is prototype of another Object.
- propertyIsEnumerable( "pName" ) - If the property cab be enumerated usinf the for-in statement.
- toLocaleString() - Returns a string representation of the object appropriate for the locale of execution environment.
- toString() - Returns a string representation of the object.
- valueOf() - Returns a string, number or boolean equivalent of the object. Return the same value as toString().
Objects that exist in the browser env (BOM/DOM) are considered host objects as they are provided & defined by host env. Host objects may/may not directly inherit from Object.
Unary Operators
Have side effect of changing the value of the variable.
Increment ++
Decrement --
Have side effect of changing the value of the variable.
Increment ++
Decrement --
- String - The string variable is converted to number and the operation applied. Converted to NaN if not a valid Number.
- Boolean - False converted to 0 & True to 1. Variable now changes to Number Type
- Object - valueOf() is called to get the number. If NaN then toString() is called. The variable Type is changed form Object to Number.
Unary Plus and Minus
Bitwise Operators
- AND = &
- NOT = ~
- OR = |
- XOR = ^
Left Shift
Right Shift
Unsigned Right Shift
Logical NOT ( ! )
May be applied to any value in ECMAScript. Always returns a Boolean value.
Logical AND ( && ) - Its different
Can be used with any type of operand not just boolean.
Does not always return Boolean.
...........
\
Functions and Reference
Four ways to call a function
Logical NOT ( ! )
May be applied to any value in ECMAScript. Always returns a Boolean value.
- Object - false
- Empty String - true
- Non-Empty String - false
- Number 0 - true
- Number other than 0 ( including Infinity ) - false
- null - true
- NaN - true
- undefined - true
alert ( !! "blue" ) = true
same as Boolean( "true" )
Logical AND ( && ) - Its different
Can be used with any type of operand not just boolean.
Does not always return Boolean.
...........
\
Functions and Reference
Four ways to call a function
- As a method (standalone fn() )
- As object method ( obj.fn() )
- As constructor function (using new fn()) - returns object
- With a function method call() or apply()
- All function calls are pass by value
- Scope chain
- There is no block level scoping in Javascript
- Context
- variable declared with var is added to current context
- A variable initialized without being declared (using var) is added to the global context
- Reference Type
- Object Type
- When defined using Object Literal notation Object constructor is not called.
- Array notation to access the properties of the Object
- Array Type
- Can hold any type of data in any slot
- Are dynamically sized and grows automatically
- Created using constructor function providing size / element(s)
- Also created using array literal notation arr = [1,2,3,4]
- When defined using array literal notation Array constructor is not called.
- Adding an element after last index increases the size if the array.
- array.length is NOT read-only. changing its value can increase/decrease size of the array.
- value instanceof Array - returns true for array. doesnt work when array from other frame is checked.. ?
- Array.isArray( arrayToTest ) - works well
- Array can behave like Stack with push( obj1, obj2.. ) and pop() operations.
- push() adds at end of the array and returns length of new Array.
- Array can also behave as Queue with shift() operation returning the first element in the array.
- unshift( obj1, obj2, ..) is reverse of shift() which add to the start of the Array.
- Array.reverse() - reverses in place
- Array.sort() - performs sorting be calling String() casting function on each element. A comparison function Array.sort(compare) taking 2 arguments can be passed to define different sorting.
- Array.concat( firstArray, secondArray) returns new array. The original array remains unchanged.
- Array.slice( startIndex, [endIndex]) - returns subarray.
- Array.splice() - can do Deletion, Insertion & Replacement
- Array.indexOf( element )
- Array.lastIndexOf ( element )
- Iteration
- every()
- filter()
- forEach()
- map()
- some()
- Array.reduce()
- Date Type
- RegEx Type
- Function Type
- Functions are Objects
- Function names are pointers.
- Each function is an instance of Function type
- Function names are pointers to Function Objects
- Function variables can be defined in 3 ways.
- function abc( param ) {}
- abc = function (param) {}
- abc = new Function(param) {} // not recommended
- Functions cant be overloaded as there is no signature for a function
- Function Declaration (no assignment) vs Function Expression (assignment)
- Function can be passed as an argument and be returned from another function.
- arguments - is array-like object that contains all parameters
- arguments.callee - the function that owns arguments object (function being called)
- this -
- is a reference to the context object
- for a function called in global scope - this refers to window
- the value of this is not defined until the function is called.
- function.caller - the reference to the function that called this function.
- length - number of named arguments that the function expects.
- prototype - is actual location of all instance methods for reference types. Method toString() and valueOf() exist on prototype.
- apply() and call() - both call a function with a specific this value (which sets up the context ?)
- first parameter is always this
- second parameter for apply() can be arguments or the array containing all the parameters.
- second parameter for call() is actual list of parameters.
- bind() - function.bind(this) - returns a function instance that is bound to a specific value.
- Primitive Wrapper Types
- String
- String methods()...
- Number
- Boolean
- Singleton Built-in Objects
- Global
- Methods and properties that otherwise dont have an owning object
- isNan(), isFinite(), parseInt(), parseFloat(), encodeURI(), encodeURIComponent()
- eval() - works like an ECMAScript interpreter that takes one argument. String representing a script to be executed. Executed code has same scope chain as that of the current context.
- Properties
- undefined
- NaN
- Infinity
- Object
- Array
- Function
- Boolean
- String
- Date
- Number
- ...
- Window Object - Web browsers implement Global Object as window object.
- Math
Constructor Function
- When new is used the value this literally means the new object/instance that will be created
- if you create a constructor function and call it without the use of the new keyword the this value will refer to the "parent" object that contains the function
No comments:
Post a Comment