2. Introduction to JavaScript
JavaScript is the most popular and incredibly powerful
scripting language.
JavaScript was designed to add interactivity to HTML pages
JavaScript is a scripting language
A scripting language is a lightweight programming language
JavaScript is usually embedded directly into HTML pages
JavaScript is an interpreted language (means that scripts execute without
preliminary compilation)
Everyone can use JavaScript without purchasing a license
3. What can JavaScript do?
JavaScript gives HTML designers a programming tool
JavaScript can react to events
A JavaScript can be set to execute when something happens, like when a page has finished
loading or when a user clicks on an HTML element
JavaScript can read and write HTML elements
A JavaScript can read and change the content of an HTML element
JavaScript can be used to validate data
A JavaScript can be used to validate form data before it is submitted to a server. This saves the
server from extra processing
4. What can JavaScript do?
JavaScript can be used to detect the visitor's browser
A JavaScript can be used to detect the visitor's browser, and - depending on the browser - load
another page specifically designed for that browser
JavaScript can be used to create cookies
A JavaScript can be used to store and retrieve information on the visitor's computer
5. JavaScript Syntax
The HTML <script> tag is used to insert a JavaScript into an HTML page.
The <script> and </script> tells where the JavaScript starts and ends.
You can place an unlimited number of scripts in your document, and you can
have scripts in both the body and the head section at the same time.
A simple example of JavaScript:
//Example 1.
<script type="text/javascript">
... some JavaScript code ...
</script>
6. Document Object Model
"The W3C Document Object Model (DOM) is a platform and language-neutral
interface that allows programs and scripts to dynamically access and update
the content, structure, and style of a document.”
The HTML DOM defines a standard for accessing and manipulating HTML
documents.
The DOM is a W3C (World Wide Web Consortium) standard.
The Dom is Platform- and language-independent.
7. HTML DOM
DOM Nodes - In the DOM, everything in an HTML document is a node.
The DOM says:
1. The entire document is a document node
2. Every HTML element is an element node
3. The text in the HTML elements are text nodes
4. Every HTML attribute is an attribute node
5. Comments are comment nodes
The HTML DOM views an HTML document as a node-tree.
All the nodes in the tree have relationships to each other.
8. Node Parent, Children & Sibling
The nodes in the node tree have a hierarchical relationship to each other.
The terms parent, child, and sibling are used to describe the relationships.
Parent nodes have children. Children on the same level are called siblings
(brothers or sisters).
In a node tree, the top node is called the root
Every node has exactly one parent node, except the root which has no
parent
A node can have any number of children
A leaf is a node with no children
Siblings are nodes with the same parent
9. Selector
jQuery selectors allow you to select and manipulate HTML element(s).
It's based on the existing CSS Selectors
All selectors in jQuery start with the dollar sign and parentheses: $()
Example :
$("p") // Tag Selector
$("#test") // ID selector
$(".test") // Class selector
10. DataTypes
Call by Value
String
Number
Boolean,Null, Undefined.
Call by reference
Array // [ ‘a’ , ‘b’ , ‘c’ ]
Object // { 0 : ’a’ , 1 : ’b’, 2 : ’c’}
JavaScript has dynamic types. This means that the same variable can be used as
different types:
var x; // Now x is undefined
var x = 5; // Now x is a Number
var x = "John"; // Now x is a String
11. Conditionals, Loops & Operators
Conditions Loops Operators
if statement for Arithmetic Operators (+ ,- ,* ,/ ,% ,++ ,--)
if...else statement while Comparison Operators (== ,!=. ,> ,< ,>= ,<=)
if...else if....else statement do while Logical (or Relational) Operators (&&, ||, !)
switch statement for in
Assignment Operators (= ,+= ,-= ,*= ,/= ,%=)
Conditional (or ternary) Operators (? :)
12. Typeof & instanceof using jQuery
typeof
It’s is a unary operator that is placed before its single operand, which can be of any type. Its
value is a string indicating the datatype of the operand.
Example:
typeof 2 // “number”
typeof {} // “object”
instanceof
The instanceof operator tests whether an object has in its prototype chain the prototype property
of a constructor.
Example:
[] instanceof Array //true
[] instanceof Object //true
13. Function
Function Syntax in JS:
function functionName(parameters) {
code to be executed
}
A function can be invoked:
When an event occurs (when a user clicks a button)
When it is invoked (called) from JavaScript code
Automatically (self invoked)
14. Scope
There are only two scopes in JS:
Local
A variable declared (using var) within a JavaScript function becomes LOCAL to the function.
The variable gets a local scope: It can only be accessed from within that function.
Local variables can have the same name in different functions, because they are only
recognized by the function where they were declared.
Arguments (parameters) work as local variables inside functions.
Local variables are created when the function starts, and deleted when the function is
completed.
Global
A variable declared outside a function, becomes GLOBAL.
The variable gets a global scope: All scripts and functions on the web page can access it.
15. Closures
Closures are functions that refer to independent (free) variables.
In other words, the function defined in the closure 'remembers' the environment in which it was
created.
function makeFunc() {
var name = "Mozilla";
function displayName() {
alert(name);
}
return displayName;
}
var myFunc = makeFunc();
myFunc();
Change page font size using JS closures
16. Events
In its most ancient form an event handler looks like this.
<a href="somewhere.html" onclick="alert('I've been clicked!')"> (de facto standardized by Netscape)
element.onclick = doSomething;
function doSomething(e) {
if (!e) var e = window.event
// e refers to the event
// this refers to the HTML element which currently handles the event
// target/srcElement refer to the HTML element the event originally took place on
}
Lit the bulb
18. Element 1
Event order Bubbling and Capturing
“If an element and one of its ancestors have an event handler for the same
event, which one should fire first?”
Netscape Model Microsoft Model W3C Model
Netscape said that the event on
element1 takes place first. This is
called event capturing.
Microsoft maintained that the event
on element2 takes precedence.
This is called event bubbling.
In the W3C event model is first
captured until it reaches the target
element and then bubbles up again.
Element 2
Element 1
Element 2
Element 1
Element 2
19. Advanced event registration model
It offers a simple way to register as many event handlers as you like for the
same event on one element.
W3C (IE9+ and others)
element.addEventListener('click',doSomething,false)
element.removeEventListener('click',spyOnUser,false)
last argument of addEventListener, it is meant to state whether the event handler should
be executed in the capturing or in the bubbling phase.
Microsoft (IE5+)
element.attachEvent('onclick',startDragDrop)
element.detachEvent('onclick',spyOnUser)
20. Benefits of add/bind Event to an element
over direct event binding
Can easily add and remove an event listener by using the addEventListener() and
removeEventListener() method respectively.
Attaches an event handler to an element without overwriting existing event handlers.
Can add many event handlers to one element.
can add many event handlers of the same type to one element, i.e two "click" events.
Can add event listeners on any HTML DOM object such as HTML elements, the HTML
document, the window object, or other objects that supports events, like the
xmlHttpRequest object.
21. Constructor and Custom Objects
JavaScript is a prototype-based language which contains no class statement.
Constructor
function Person(gender) {
this.gender = gender;
alert('Person instantiated');
}
Custom Objects
var person1 = new Person('Male');
var person2 = new Person('Female');
24. Encapsulation
Encapsulation is the packing of data and functions into a
single component. ~ Wiki
A method of bundling the data and methods that use the
data. ~ MDN
25. Exp.
function Class_ABC() {
var msg = “Hello Mr.” ; // private
data
var Reply = function (){ // private
method
alert(‘Yes, How may i help you.’)
}
this.x = 2; //
public data
this.sum = function () { //
public member
alert('Add x with 10: ' + (this.x + 10))
}
}
var instance = new Class_ABC()
instance.sum(); // output Add x with 10: 12
instance.x // output 2
instance msg // output undefined
function xyz() {
var x = 10; // private
var y = 20; // private
return {
add : function(){ // public
alert(x +y)
},
sub : function(){ // public
alert(y-x)
}
} //end of return
}// end of function
var p = xyz();
p.add() // output 30
p.sub() // output 10
26. Abstraction
● Abstracting only the aspects/information which are
relevant for a particular purpose/user.
OR
● Suppressing the more complex details below the
current level.
27. Inheritance
A class can inherit characteristics from another class.
Different ways to achieve inheritance
● Prototype-based
● By using call/Apply Function
28. function Person(gender) {
this.gender = gender;
}
Person.prototype.sayGender = function () {
alert(this.gender);
};
var person1 = new Person('Male');
person1.sayGender(); // alerts 'Male'
Inheritance (Prototype-based)
29. function baseClass() {
this.x = 2;
this.y = 4;
this.sum = function () {
alert('Hi, i am defined inside base
class: ' + (this.x + this.y));
}
}
Inheritance(By using call Function)
function subClass() {
baseClass.call(this); // to inherit base class members
alert(this.x)
alert(this.y)
}
var inst = new subClass();
inst.sum();
30. Type of Inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multiple Inheritance
31. Polymorphism
… Poly means "many" and morphism means "forms".
Types:
● function overloading
● function overriding
Different classes might define the same method or property.
32. function baseClass() {
this.x = 2;
this.y = 4;
this.sum = function () {
alert('Hi, i am defined inside base
class: ' + (this.x + this.y))
}
}
Polymorphism
function subClass() {
baseClass.call(this); // to inherit base class members
this.sum = function () {
alert('Hi, i am defined inside subClass and baseClass
sum function is overridden by me: ' + (this.x + this.y + 10))
}
}
x = new baseClass();
x.sum();
y = new subClass();
y.sum();
33. Qunit : JavaScript unit testing framework
QUnit.test( "hello test", function( assert ) {
assert.equal( 1 == "1", "Passed!" );
});
● We maintain separate copy
of our testable code and
production ready code.
● It lets you test private
functions without exposing
them on live.
34. Grunt : Automating UI processes
In front end team resource management is
automated using GRUNT (The JavaScript Task
Runner)
Dependencies
node.js
grunt-plugins
Gruntfile
package.json
By including Grunt in our projects all of the above
tasks are now just single command away.
http://gruntjs.com/ This site has all the information
about how to make a local grunt setup.
Compressing Javascript and CSS
files
grunt-yui-compressor
Merging JS modules into single
file
grunt--concat
Compile Sass to CSS using
Compass
grunt-contrib-compass
Validate files with JSHint grunt-contrib-jshint
Run predefined tasks whenever
watched file patterns are
added, changed or deleted.
grunt-contrib-watch
Minify images grunt-contrib-imagemin
Clean files and folders grunt-contrib-clean
Project creation with required
folder structure.
grunt-shell
35. Optimization
Level of the scope chain must be minimum.
Use module/feature specific checks in case of cross browser issues.
Array’s length should not be recomputed in loops.
Include scripts at end of the page or use dynamic inclusions.
Minify and gzip the resources.