SlideShare a Scribd company logo
1 of 36
javaScript basics
Naukri FED
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
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
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
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>
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.
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.
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
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
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
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 (? :)
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
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)
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.
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
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
Events
Input Events Mouse Events Click Events Load Events
● onfocus
● onblur
● onchange
(input, select box)
● onselect
● onsubmit
● onreset
● onkeydown
● onkeypress
● onkeyup
● onmouseover
● onmouseout
● onmousedown
● onmouseup
● onmousemove
● onmouseout
● onmouseover
● onmouseout
● onclick
● ondblclick
● onload
(page, image)
● onerror
● onunload
● onresize
● DOMContentLoaded
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
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)
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.
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');
OOPs
Pillars of OOPS
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
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
Abstraction
● Abstracting only the aspects/information which are
relevant for a particular purpose/user.
OR
● Suppressing the more complex details below the
current level.
Inheritance
A class can inherit characteristics from another class.
Different ways to achieve inheritance
● Prototype-based
● By using call/Apply Function
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)
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();
Type of Inheritance
Single Inheritance
Multilevel Inheritance
Hierarchical Inheritance
Hybrid Inheritance
Multiple Inheritance
Polymorphism
… Poly means "many" and morphism means "forms".
Types:
● function overloading
● function overriding
Different classes might define the same method or property.
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();
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.
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
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.
{ THANKS }

More Related Content

What's hot

Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy stepsprince Loffar
 
Ng init | EPI Sousse
Ng init | EPI SousseNg init | EPI Sousse
Ng init | EPI SousseHamdi Hmidi
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events WebStackAcademy
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM ManipulationsYnon Perek
 
KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7phuphax
 
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web TechnologyAyes Chinmay
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event HandlingWebStackAcademy
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core DataInferis
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming WebStackAcademy
 
Multi-threaded CoreData Done Right
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Rightmorrowa_de
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with WebAkshay Mathur
 
JS Libraries and jQuery Overview
JS Libraries and jQuery OverviewJS Libraries and jQuery Overview
JS Libraries and jQuery OverviewAleksandr Motsjonov
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contextsMatthew Morey
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging TechniquesWebStackAcademy
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects WebStackAcademy
 

What's hot (20)

Learn javascript easy steps
Learn javascript easy stepsLearn javascript easy steps
Learn javascript easy steps
 
Ajax xml json
Ajax xml jsonAjax xml json
Ajax xml json
 
Ng init | EPI Sousse
Ng init | EPI SousseNg init | EPI Sousse
Ng init | EPI Sousse
 
jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events jQuery -Chapter 2 - Selectors and Events
jQuery -Chapter 2 - Selectors and Events
 
JavaScript DOM Manipulations
JavaScript DOM ManipulationsJavaScript DOM Manipulations
JavaScript DOM Manipulations
 
KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7KMUTNB - Internet Programming 4/7
KMUTNB - Internet Programming 4/7
 
Dom
DomDom
Dom
 
Unit 4(it workshop)
Unit 4(it workshop)Unit 4(it workshop)
Unit 4(it workshop)
 
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web TechnologyInternet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
Internet and Web Technology (CLASS-7) [XML and AJAX] | NIC/NIELIT Web Technology
 
Angular - Chapter 4 - Data and Event Handling
 Angular - Chapter 4 - Data and Event Handling Angular - Chapter 4 - Data and Event Handling
Angular - Chapter 4 - Data and Event Handling
 
Adventures in Multithreaded Core Data
Adventures in Multithreaded Core DataAdventures in Multithreaded Core Data
Adventures in Multithreaded Core Data
 
Jsp intro
Jsp introJsp intro
Jsp intro
 
Lecture 5 javascript
Lecture 5 javascriptLecture 5 javascript
Lecture 5 javascript
 
Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming  Angular - Chapter 2 - TypeScript Programming
Angular - Chapter 2 - TypeScript Programming
 
Multi-threaded CoreData Done Right
Multi-threaded CoreData Done RightMulti-threaded CoreData Done Right
Multi-threaded CoreData Done Right
 
Getting Started with Web
Getting Started with WebGetting Started with Web
Getting Started with Web
 
JS Libraries and jQuery Overview
JS Libraries and jQuery OverviewJS Libraries and jQuery Overview
JS Libraries and jQuery Overview
 
Core Data with multiple managed object contexts
Core Data with multiple managed object contextsCore Data with multiple managed object contexts
Core Data with multiple managed object contexts
 
JavaScript - Chapter 15 - Debugging Techniques
 JavaScript - Chapter 15 - Debugging Techniques JavaScript - Chapter 15 - Debugging Techniques
JavaScript - Chapter 15 - Debugging Techniques
 
jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects  jQuery - Chapter 3 - Effects
jQuery - Chapter 3 - Effects
 

Viewers also liked

BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊN
BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊNBÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊN
BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊNCGFED
 
Rising Asia - Inaugural Issue, April 2015
Rising Asia - Inaugural Issue, April 2015Rising Asia - Inaugural Issue, April 2015
Rising Asia - Inaugural Issue, April 2015Rumman Ahamed
 
Eiiiiiiiiiiii
EiiiiiiiiiiiiEiiiiiiiiiiii
Eiiiiiiiiiiiialexlur
 
Team 1 c IMT oral presentation
Team 1 c IMT oral presentationTeam 1 c IMT oral presentation
Team 1 c IMT oral presentationmra21
 
Diskripsi diri
Diskripsi diriDiskripsi diri
Diskripsi diridanielpuji
 
International trade course 3
International trade course 3International trade course 3
International trade course 3Yudy Yunardy
 
Hampshire Constabulary Renuneration Planning SFIA
Hampshire Constabulary Renuneration Planning SFIAHampshire Constabulary Renuneration Planning SFIA
Hampshire Constabulary Renuneration Planning SFIASFIA User Forum
 
5 kinesis lightning
5 kinesis lightning5 kinesis lightning
5 kinesis lightningBigDataCamp
 
Stokvis Tapes
Stokvis TapesStokvis Tapes
Stokvis Tapesstokvis
 
Pass Love Charity Foundation (PLCF)
Pass Love Charity Foundation (PLCF)Pass Love Charity Foundation (PLCF)
Pass Love Charity Foundation (PLCF)PassLoveCharity
 
CMG Recommendation Letter PSB JPG
CMG Recommendation Letter PSB JPGCMG Recommendation Letter PSB JPG
CMG Recommendation Letter PSB JPGPia Sanchez
 

Viewers also liked (20)

BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊN
BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊNBÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊN
BÍ QUYẾT QUẢN LÝ HIỆU QUẢ CÂU LẠC BỘ CHA MẸ VÀ VỊ THÀNH NIÊN, THANH NIÊN
 
Rising Asia - Inaugural Issue, April 2015
Rising Asia - Inaugural Issue, April 2015Rising Asia - Inaugural Issue, April 2015
Rising Asia - Inaugural Issue, April 2015
 
Eiiiiiiiiiiii
EiiiiiiiiiiiiEiiiiiiiiiiii
Eiiiiiiiiiiii
 
Team 1 c IMT oral presentation
Team 1 c IMT oral presentationTeam 1 c IMT oral presentation
Team 1 c IMT oral presentation
 
Ggdds
GgddsGgdds
Ggdds
 
How real is race?
How real is race?How real is race?
How real is race?
 
Fghfdgh
FghfdghFghfdgh
Fghfdgh
 
Numeración romana
Numeración romanaNumeración romana
Numeración romana
 
Diskripsi diri
Diskripsi diriDiskripsi diri
Diskripsi diri
 
Statement to Guardian
Statement to GuardianStatement to Guardian
Statement to Guardian
 
Status report1
Status report1Status report1
Status report1
 
International trade course 3
International trade course 3International trade course 3
International trade course 3
 
Visvi
VisviVisvi
Visvi
 
Hampshire Constabulary Renuneration Planning SFIA
Hampshire Constabulary Renuneration Planning SFIAHampshire Constabulary Renuneration Planning SFIA
Hampshire Constabulary Renuneration Planning SFIA
 
5 kinesis lightning
5 kinesis lightning5 kinesis lightning
5 kinesis lightning
 
Stokvis Tapes
Stokvis TapesStokvis Tapes
Stokvis Tapes
 
Abc c program
Abc c programAbc c program
Abc c program
 
Pass Love Charity Foundation (PLCF)
Pass Love Charity Foundation (PLCF)Pass Love Charity Foundation (PLCF)
Pass Love Charity Foundation (PLCF)
 
Guinea-Bissau: phosphate for food
Guinea-Bissau: phosphate for foodGuinea-Bissau: phosphate for food
Guinea-Bissau: phosphate for food
 
CMG Recommendation Letter PSB JPG
CMG Recommendation Letter PSB JPGCMG Recommendation Letter PSB JPG
CMG Recommendation Letter PSB JPG
 

Similar to JS basics

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom ManipulationMohammed Arif
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingHoat Le
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTAAFREEN SHAIKH
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationSoumen Santra
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONSyed Moosa Kaleem
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGProf Ansari
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programmingFulvio Corno
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript TutorialDHTMLExtreme
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQueryLaurence Svekis ✔
 
javascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptjavascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptLalith86
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32Bilal Ahmed
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templatingbcruhl
 
JavaScript: Implementations And Applications
JavaScript: Implementations And ApplicationsJavaScript: Implementations And Applications
JavaScript: Implementations And ApplicationsPragya Pai
 

Similar to JS basics (20)

JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
eXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction TrainingeXo SEA - JavaScript Introduction Training
eXo SEA - JavaScript Introduction Training
 
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPTHSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
HSC INFORMATION TECHNOLOGY CHAPTER 3 ADVANCED JAVASCRIPT
 
JavaScript
JavaScriptJavaScript
JavaScript
 
Scripting The Dom
Scripting The DomScripting The Dom
Scripting The Dom
 
J Query
J QueryJ Query
J Query
 
JavaScript with Syntax & Implementation
JavaScript with Syntax & ImplementationJavaScript with Syntax & Implementation
JavaScript with Syntax & Implementation
 
Event Programming JavaScript
Event Programming JavaScriptEvent Programming JavaScript
Event Programming JavaScript
 
jQuery
jQueryjQuery
jQuery
 
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSONAn introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
An introduction to DOM , JAVASCRIPT , JQUERY, AJAX and JSON
 
INTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMINGINTRODUCTION TO CLIENT SIDE PROGRAMMING
INTRODUCTION TO CLIENT SIDE PROGRAMMING
 
Introduction to Javascript programming
Introduction to Javascript programmingIntroduction to Javascript programming
Introduction to Javascript programming
 
J query
J queryJ query
J query
 
Basic JavaScript Tutorial
Basic JavaScript TutorialBasic JavaScript Tutorial
Basic JavaScript Tutorial
 
Web Development Introduction to jQuery
Web Development Introduction to jQueryWeb Development Introduction to jQuery
Web Development Introduction to jQuery
 
javascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.pptjavascript Event Handling and introduction to event.ppt
javascript Event Handling and introduction to event.ppt
 
Java script
Java scriptJava script
Java script
 
CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32CS101- Introduction to Computing- Lecture 32
CS101- Introduction to Computing- Lecture 32
 
Javascript Templating
Javascript TemplatingJavascript Templating
Javascript Templating
 
JavaScript: Implementations And Applications
JavaScript: Implementations And ApplicationsJavaScript: Implementations And Applications
JavaScript: Implementations And Applications
 

JS basics

  • 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
  • 17. Events Input Events Mouse Events Click Events Load Events ● onfocus ● onblur ● onchange (input, select box) ● onselect ● onsubmit ● onreset ● onkeydown ● onkeypress ● onkeyup ● onmouseover ● onmouseout ● onmousedown ● onmouseup ● onmousemove ● onmouseout ● onmouseover ● onmouseout ● onclick ● ondblclick ● onload (page, image) ● onerror ● onunload ● onresize ● DOMContentLoaded
  • 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');
  • 22. OOPs
  • 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.

Editor's Notes

  1. Ankit
  2. To be updated
  3. Saeed polymorphishm
  4. Saeed polymorphism
  5. Saeed Content & Demo
  6. Saeed Content & Demo
  7. Saeed polymorphishm
  8. Ankit information