SlideShare a Scribd company logo
WEB
FRAMEWORKS
1Monica Deshmane(H.V.Desai College,Pune)
Syllabus : What we learn?
See link - https://prezi.com/view/NNmyKQS4eeL9lz89bQyz/
 Javascript basics
 Introduction to Node JS (framework to run JS without browser anywhere)
• Node JS Modules
• NPM
• Web Server
• File system
• Events
• Databases
• Express JS
 Introduction to DJango (quick & easy to develop app with minimum code)
 Setup
 URL pattern
 Forms &Validation
Monica Deshmane(H.V.Desai College,Pune) 2
chap 1 Java Script Basics
1.1 Java Script data types
1.2 Variables, Functions, Events,
Regular Expressions
1.3 Array and Objects in Java Script
1.4 Java Script HTML DOM
1.5 Promises and Callbacks
Introduction
JavaScript is the scripting language for HTML
and understood by the Web.
JavaScript is easy to learn.
JavaScript is made up of the 3 languages :
1. HTML for look & Feel.
2. CSS to specify the layout or style.
3. JavaScript for Event Handling.
The <script> Tag
Ex. How to write JS?
<script type="text/javascript">
var i = 10;
if (i < 5) {
// some code
}
</script>
The <script> Tag
Attributes of <script>
1. async- script is executed asynchronously (only
for external scripts)
2. charset –charset Specifies the character
encoding format.
3. defer -Specifies that script is executed when
the page has finished parsing
4. src - Specifies the URL of an external script file
5. type - Specifies the media type of the script
6. Lang- To specify which language to use.
The <script> Tag in
< Body>
Script gets executed automatcally when program runs
or we can call by function call.
<html>
<body>
<p id=“p1">A Paragraph</p>
<Input type="button" onclick="myFunction()“
value=“change”>
<script>
function myFunction() {
document.getElementById(“p1").innerHTML =
"Paragraph changed.";
}
</script>
</body>
</html>
The <script> Tag in
< Head> The function must be invoked (called) when event
occurs .
Ex. button is clicked:
<html>
<head> <script>
function myFunction() {
document.getElementById(“p1").innerHTML
= "Paragraph changed.";
}
</script></head>
<body>
<p id=“p1">A Paragraph</p>
<Input type="button" onclick="myFunction()">Try it</Input>
</body></html>
https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
Java Script data types
1) String
var Name = “parth"; // String
2) Number
var length = 36; // Number
3) Boolean
Booleans can only have two values: true or false.
4) Undefined
var x = 5;
var y = 5;
(x == y) // Returns true
typeof (3) // Returns "number" to return data type of variable
typeof undefined // undefined
monica Deshmane(H.V.Desai College,Pune)
1) Primitaive data type
Java Script data types
1) Function
function myFunction() { }
2) Object
var x = {firstName:"John", lastName:“Ray"}; // Object
3) Array
var cars = [“suzuki", "VagonR", "BMW"]; //array
var person = null; //null
//diffrence between null & undefined
1) typeof undefined // undefined
typeof null // object
2) null === undefined // false
null == undefined // true
monica Deshmane(H.V.Desai College,Pune)
2)complex data types
JS Types:Revise
You can divide JavaScript types into 2 groups
1) primitive - are number, Boolean, string, null
2) complex -are array ,functions ,and objects
//primitive
Var A=5;
Var B=A;
B=6;
A; //5
B; //6
//complex or reference types
Var A=[2,3];
Var B=A;
B[0]=3;
A[0]; //3
B[0]; //3
JavaScript variables are used for storing data values.
Same rules of variables in java are followed.
var x = 5;
var y = 6;
var z = x + y;
also learn-
local variables,
global variables,
static variables
Java Script variables
monica Deshmane(H.V.Desai College,Pune)
A JavaScript function is a block of code to perform a
particular task.
executed when someone invokes / calls it.
Syntax:-
function name(para1, para2, para3)
{
// code to be executed
}
Java Script Functions
monica Deshmane(H.V.Desai College,Pune)
Function Invocation i.e call needed.
Return value- Functions often compute a return value.
The return value is "returned" back to the "caller".
Example-
var x = myFunction(10, 3);
// Function is called, return value will assigned to x
function myFunction(a, b)
{
return a * b; // Function returns the product of a and b
}
Java Script Functions
monica Deshmane(H.V.Desai College,Pune)
var f=function f()
{
typeof f== “function”; //true
window==this; //true
//as this is global object
}
.call & .apply method-To change reference of this to any
other object when calling function.
function a() {this.a==‘b’; //true}
funcation a(b,c){
b==‘first’; //true
c==‘second’; //true
}
a.call((a:’b’),’first’,’second’);
//call takes list of parameters to pass function
a.apply({a:’b’},[’first’,’second’]);
//apply takes array of parameters to pass function
monica
Deshmane(H.V.Desai
College,Pune)
Some concepts about function..
Java Script Events
Event Description
onChange An HTML element has been changed
onClick The user clicks an HTML element / control
onMouseOver The user moves the mouse over an HTML element
onMouseOut The user moves the mouse away from an HTML
element
onKeydown The hits pushes a keyboard key
onLoad After loading the page
onFocus When perticular control is hilighted
See demo online
monica Deshmane(H.V.Desai College,Pune)
•e.g.
•<button onclick="displayDate()“>The time is?</button>
<body onload=“display()”>….</body>
<input type=text name=“txt” onmouseover = “display()”>
<input type=text name=“txt” onFocus = “display()”>
Examples of events
Regular Expressions( RE)
monica Deshmane(H.V.Desai College,Pune)
A regular expression is a sequence of
characters that forms a pattern.
The pattern can be used for
1)search
2)replace
3)Match
A regular expression can be made by a
single character, or a more complicated
/mixed patterns.
Patterns
Character classes
[:alum:] Alphanumeric characters [0-9a-zA-Z]
[:alpha:] Alphabetic characters [a-zA-Z]
[:blank:] space and tab [ t]
[:digit:] Digits [0-9]
[:lower:] Lower case letters [a-z]
[:upper:] Uppercase letters [A-Z]
[:xdigit:] Hexadecimal digit [0-9a-fA-F]
range of characters ex. [‘aeiou’]
Patterns continue…
? 0 or 1
* 0 or more
+ 1 or more
{n} Exactly n times
{n,m} Atleast n, no more than m
times
{n,} Atleast n times
n newline
t tab
^ beginning
$ end
Using String Methods
monica Deshmane(H.V.Desai College,Pune)
the two string methods used for RE are search() and replace().
1. The search() method uses an expression to search for a match,
and returns the position of the match.
var pos = str.search(“/this/”);
2. The replace() method returns a modified string where the pattern
is replaced.
var txt = str.replace(“/is/”, “this");
3. match() used to match pattern
“hi234”.match(/^ (a-z) +(d{3})$/)
4. exec() -Syntax- pattern.exec(string);
The exec() method returns the matched text if it finds a match,
otherwise it returns null.
“/(hey|ho)/”.exec('h') //h
Array in Java Script
monica Deshmane(H.V.Desai College,Pune)
1. Array creation
• var arr1 = new Array(); OR
• var arr2 = [ ];
arr2.push(1);
arr2.push(2); //[1,2]
arr1.sort();
• var arr3 = [ ‘mat', 'rat', 'bat' ];
2. Length
arr2.length;
console.log(arr2);
3. To delete element from array
arr3.splice(2, 2);
arr.pop(); //see demo on JS.do
Array splice in Java Script
monica Deshmane(H.V.Desai College,Pune)
<script>
var lang = ["HTML", "CSS", "JS", "Bootstrap"];
document.write(lang + "<br>");
var removed = lang.splice(2, 1, 'PHP', ‘python')
document.write(lang + "<br>");
// HTML,CSS,JS,Bootstrap
document.write(removed + "<br>");
// HTML,CSS,PHP,python,Bootstrap
// No Removing only Insertion from 2nd index from the ending
lang.splice(-2, 0, 'React') // JS
document.write(lang)
// HTML,CSS,PHP,React,python,Bootstrap
</script>
Array continue…
monica Deshmane(H.V.Desai College,Pune)
Array is like u so before the typeof operator will
return “object” for arrays more times however you
want to check that array is actually an array.
Array.isArray returns true for arrays and False for
any other values.
Array.isArray( new array) // true
Array.isArray( [ ] ) // true
Array.isArray( null) // false
Array.isArray(arguments ) //false
Array continue…
monica Deshmane(H.V.Desai College,Pune)
See –tutorials point javascript arrays
array methods
• to loop over an array you can use for each (Similar to jquery $.each)
[1,2,3].foreach(function value)
{ console.log (value ); }
•To filter elements out of array you can use filter (similar two jQuery
grep)
[1,2,3].foreach(function value)
{ return value < 3; } //will return [ 1, 2]
•to change value of of each item you can use map (similar to Jquery
map)
[ 5,10 ,15].map function (value)
{ return value*2; } // will return [10 ,20 ,30]
• also available but less commonly used are the methods-
reduce , reduceRight and lastIndexOf.
Array continue…
monica Deshmane(H.V.Desai College,Pune)
•reduceRight:-Subtract the numbers in the array, starting from the right:
<script>
var numberarr= [175, 50, 25];
document.getElementById(“p1").innerHTML =
numberarr.reduceRight(myFunc);
function myFunc(total, num) {
return total - num;
}
•Reduce-from left to right
•lastIndexOf-
const animals = ['Dog', 'Tiger', 'Penguin','Dog'];
console.log(animals.lastIndexOf('Dog'));// expected output: 3
console.log(animals.lastIndexOf('Tiger'));// expected output: 1
•Object Creation
var obj1 = new Object();
var obj2 = { };
var subject = { first_name: "HTML", last_name: "CSS“ ,
reference: 320 ,website: "java2s.com" };
•add a new property
subject.name= "brown"; OR
subject["name"] = "brown";
•To delete a new property
delete subject.name;
•To get all keys from object
var obj={a:’aaa’, b:’bbb’ ,c:’ccc’};
Object.keys(obj); //[‘a’ ,’b’, ‘c’]
Objects in Java Script
HTML DOM
The HTML DOM is a standard object model and
programming interface for HTML.
It contains -The HTML elements as objects
-The properties of all HTML elements
-The methods to access all HTML elements
-The events for all HTML elements
DOM CSS- The HTML DOM allows JavaScript to change the
style of HTML elements.
DOM Animation- create HTML animations using JavaScript
DOM Events- allows JavaScript to react to HTML events by event
handlers & event Listeners.
HTML DOM elements are treated as nodes ,in which elements
can be added by createElement() or appendChild()
& deleted nodes using remove() or removeChild().
HTML DOM continue…
Promises & callback
- The promises in Javascript are just that, promises it means that we will do
everything possible to achieve the expected result. But, we also know that a
promise cannot always be fulfilled for some reason.
Just as a promise is in real life, it is in Javascript, represented in another way.
Promises
Example
let promise = new Promise(function(resolve, reject)
{ // task to accomplish your promise
if(/* everything turned out fine */)
{ resolve('Stuff worked') }
else { // for some reason the promise doesn't fulfilled
reject(new Error('it broke'))
}
});
Promises have three unique states:
1. Pending: asynchronous operation has not been completed
yet.
2. Fulfilled: operation has completed and returns a value.
3. Rejected: The asynchronous operation fails and the
reason why it failed is indicated.
Callback function
will be executed when an asynchronous operation has been
completed.
A callback is passed as an argument to an asynchronous operation.
Normally, this is passed as the last argument of the function.
When a function simply accepts another function as an argument, this
contained function is known as a callback function.
Callback functions are written like :
function sayHello()
{ console.log('Hello everyone');}
setTimeout( sayHello( ), 3000);
What we did in the above example was, first to define a function that
prints a message to the console. After that, we use a timer
called setTimeout (this timer is a native Javascript function). This timer is
an asynchronous operation that executes the callback after a certain time.
In this example, after 3000ms (3 seconds) will be executed the
sayHello() function.
Difference between callback and promises
1. promises are easy for running asynchronous
tasks to feel like synchronous and also provide
catching mechanism which are not in callbacks.
2. Promises are built over callbacks.
3. Promises are a very mighty abstraction, allow
clean and better code with less errors.
4. In promises, we attach callbacks on the returned
promise object. For callback approach, we
normally just pass a callback into a function that
would then get called upon completion in order to
get the result of something.
.
34Monica Deshmane(H.V.Desai College,Pune)

More Related Content

What's hot (20)

PDF
Advanced task management with Celery
Mahendra M
 
PPTX
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Sencha
 
PPT
Tech talk
Preeti Patwa
 
PDF
Chat Room System using Java Swing
Tejas Garodia
 
PDF
JavaScript 101
ygv2000
 
PPT
Jsp/Servlet
Sunil OS
 
PDF
Performance Optimization and JavaScript Best Practices
Doris Chen
 
PPT
ExtJs Basic Part-1
Mindfire Solutions
 
PDF
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
PDF
Node Boot Camp
Troy Miles
 
PDF
Celery - A Distributed Task Queue
Duy Do
 
PDF
Mongoose: MongoDB object modelling for Node.js
Yuriy Bogomolov
 
PDF
iOS 2 - The practical Stuff
Petr Dvorak
 
PDF
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
PDF
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
PDF
Codegeneration With Xtend
Sven Efftinge
 
PDF
Functionnal view modelling
Hugo Saynac
 
PPTX
J Query The Write Less Do More Javascript Library
rsnarayanan
 
PPT
Javascript and Jquery Best practices
Sultan Khan
 
PDF
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 
Advanced task management with Celery
Mahendra M
 
SenchaCon 2016: Modernizing the Ext JS Class System - Don Griffin
Sencha
 
Tech talk
Preeti Patwa
 
Chat Room System using Java Swing
Tejas Garodia
 
JavaScript 101
ygv2000
 
Jsp/Servlet
Sunil OS
 
Performance Optimization and JavaScript Best Practices
Doris Chen
 
ExtJs Basic Part-1
Mindfire Solutions
 
Utopia Kindgoms scaling case: From 4 to 50K users
Jaime Buelta
 
Node Boot Camp
Troy Miles
 
Celery - A Distributed Task Queue
Duy Do
 
Mongoose: MongoDB object modelling for Node.js
Yuriy Bogomolov
 
iOS 2 - The practical Stuff
Petr Dvorak
 
JavaScript and UI Architecture Best Practices
Siarhei Barysiuk
 
Ten useful JavaScript tips & best practices
Ankit Rastogi
 
Codegeneration With Xtend
Sven Efftinge
 
Functionnal view modelling
Hugo Saynac
 
J Query The Write Less Do More Javascript Library
rsnarayanan
 
Javascript and Jquery Best practices
Sultan Khan
 
Workshop 8: Templating: Handlebars, DustJS
Visual Engineering
 

Similar to java script (20)

PPTX
11. session 11 functions and objects
Phúc Đỗ
 
PDF
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
PPTX
Intro to Javascript
Anjan Banda
 
DOCX
WD programs descriptions.docx
anjani pavan kumar
 
PPSX
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
PDF
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
PPTX
Developing web-apps like it's 2013
Laurent_VB
 
PDF
Drupaljam xl 2019 presentation multilingualism makes better programmers
Alexander Varwijk
 
PPTX
JQuery Presentation
Sony Jain
 
PPTX
Java script advance-auroskills (2)
BoneyGawande
 
PDF
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
PDF
ZendCon2010 The Doctrine Project
Jonathan Wage
 
PPTX
Php & my sql
Norhisyam Dasuki
 
PPTX
How to Bring Common UI Patterns to ADF
Luc Bors
 
PPTX
What is new in Java 8
Sandeep Kr. Singh
 
PPT
jQuery for beginners
Divakar Gu
 
PDF
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
PDF
lab4_php
tutorialsruby
 
PDF
lab4_php
tutorialsruby
 
PPTX
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
11. session 11 functions and objects
Phúc Đỗ
 
Unit Testing Express and Koa Middleware in ES2015
Morris Singer
 
Intro to Javascript
Anjan Banda
 
WD programs descriptions.docx
anjani pavan kumar
 
DIWE - Advanced PHP Concepts
Rasan Samarasinghe
 
HelsinkiJS meet-up. Dmitry Soshnikov - ECMAScript 6
Dmitry Soshnikov
 
Developing web-apps like it's 2013
Laurent_VB
 
Drupaljam xl 2019 presentation multilingualism makes better programmers
Alexander Varwijk
 
JQuery Presentation
Sony Jain
 
Java script advance-auroskills (2)
BoneyGawande
 
JavaScript(Es5) Interview Questions & Answers
Ratnala Charan kumar
 
ZendCon2010 The Doctrine Project
Jonathan Wage
 
Php & my sql
Norhisyam Dasuki
 
How to Bring Common UI Patterns to ADF
Luc Bors
 
What is new in Java 8
Sandeep Kr. Singh
 
jQuery for beginners
Divakar Gu
 
How te bring common UI patterns to ADF
Getting value from IoT, Integration and Data Analytics
 
lab4_php
tutorialsruby
 
lab4_php
tutorialsruby
 
EContent_11_2023_04_09_11_30_38_Unit_3_Objects_and_Classespptx__2023_03_20_12...
vekariyakashyap
 
Ad

More from monikadeshmane (19)

PPTX
File system node js
monikadeshmane
 
PPTX
Nodejs buffers
monikadeshmane
 
PPTX
Nodejs basics
monikadeshmane
 
PPTX
Chap 5 php files part-2
monikadeshmane
 
PPTX
Chap 5 php files part 1
monikadeshmane
 
PPTX
Chap4 oop class (php) part 2
monikadeshmane
 
PPTX
Chap4 oop class (php) part 1
monikadeshmane
 
PPTX
Chap 3php array part4
monikadeshmane
 
PPTX
Chap 3php array part 3
monikadeshmane
 
PPTX
Chap 3php array part 2
monikadeshmane
 
PPTX
Chap 3php array part1
monikadeshmane
 
PPTX
PHP function
monikadeshmane
 
PPTX
php string part 4
monikadeshmane
 
PPTX
php string part 3
monikadeshmane
 
PPTX
php string-part 2
monikadeshmane
 
PPTX
PHP string-part 1
monikadeshmane
 
PPT
ip1clientserver model
monikadeshmane
 
PPTX
Chap1introppt2php(finally done)
monikadeshmane
 
PPTX
Chap1introppt1php basic
monikadeshmane
 
File system node js
monikadeshmane
 
Nodejs buffers
monikadeshmane
 
Nodejs basics
monikadeshmane
 
Chap 5 php files part-2
monikadeshmane
 
Chap 5 php files part 1
monikadeshmane
 
Chap4 oop class (php) part 2
monikadeshmane
 
Chap4 oop class (php) part 1
monikadeshmane
 
Chap 3php array part4
monikadeshmane
 
Chap 3php array part 3
monikadeshmane
 
Chap 3php array part 2
monikadeshmane
 
Chap 3php array part1
monikadeshmane
 
PHP function
monikadeshmane
 
php string part 4
monikadeshmane
 
php string part 3
monikadeshmane
 
php string-part 2
monikadeshmane
 
PHP string-part 1
monikadeshmane
 
ip1clientserver model
monikadeshmane
 
Chap1introppt2php(finally done)
monikadeshmane
 
Chap1introppt1php basic
monikadeshmane
 
Ad

Recently uploaded (20)

PPTX
Ghent University Global Campus: Overview
Ghent University Global Campus
 
PPTX
Fetus mudaliar. Obstetrics and gynaecology
Parvathy121069
 
PDF
Plankton and Fisheries Bovas Joel Notes.pdf
J. Bovas Joel BFSc
 
PPTX
Microbiome_Engineering_Poster_Fixed.pptx
SupriyaPolisetty1
 
PDF
EXploring Nanobiotechnology: Bridging Nanoscience and Biology for real world ...
Aamena3
 
PDF
BlackBody Radiation experiment report.pdf
Ghadeer Shaabna
 
PPTX
3-measurement-161127184347.pptx in science
AizaRazonado
 
PDF
thesis dr Zahida and samia on plasma physics.pdf
HamzaKhalid267437
 
PDF
Integrating Lifestyle Data into Personalized Health Solutions (www.kiu.ac.ug)
publication11
 
PPTX
Q1_Science 8_Week3-Day 1.pptx science lesson
AizaRazonado
 
PPTX
Cerebellum_ Parts_Structure_Function.pptx
muralinath2
 
PDF
History of cage culture-J. Bovas Joel.pdf
J. Bovas Joel BFSc
 
PDF
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
PDF
GUGC Research Overview (December 2024)
Ghent University Global Campus
 
PDF
soil and environmental microbiology.pdf
Divyaprabha67
 
PDF
Plant growth promoting bacterial non symbiotic
psuvethapalani
 
PDF
20250603 Recycling 4.pdf . Rice flour, aluminium, hydrogen, paper, cardboard.
Sharon Liu
 
DOCX
Analytical methods in CleaningValidation.docx
Markus Janssen
 
PPTX
Congestive Heart failure for pharmacology topic hehe
oceangunnu
 
PDF
Webinar: World's Smallest Pacemaker
Scintica Instrumentation
 
Ghent University Global Campus: Overview
Ghent University Global Campus
 
Fetus mudaliar. Obstetrics and gynaecology
Parvathy121069
 
Plankton and Fisheries Bovas Joel Notes.pdf
J. Bovas Joel BFSc
 
Microbiome_Engineering_Poster_Fixed.pptx
SupriyaPolisetty1
 
EXploring Nanobiotechnology: Bridging Nanoscience and Biology for real world ...
Aamena3
 
BlackBody Radiation experiment report.pdf
Ghadeer Shaabna
 
3-measurement-161127184347.pptx in science
AizaRazonado
 
thesis dr Zahida and samia on plasma physics.pdf
HamzaKhalid267437
 
Integrating Lifestyle Data into Personalized Health Solutions (www.kiu.ac.ug)
publication11
 
Q1_Science 8_Week3-Day 1.pptx science lesson
AizaRazonado
 
Cerebellum_ Parts_Structure_Function.pptx
muralinath2
 
History of cage culture-J. Bovas Joel.pdf
J. Bovas Joel BFSc
 
Preserving brand authenticity amid AI-driven misinformation: Sustaining consu...
Selcen Ozturkcan
 
GUGC Research Overview (December 2024)
Ghent University Global Campus
 
soil and environmental microbiology.pdf
Divyaprabha67
 
Plant growth promoting bacterial non symbiotic
psuvethapalani
 
20250603 Recycling 4.pdf . Rice flour, aluminium, hydrogen, paper, cardboard.
Sharon Liu
 
Analytical methods in CleaningValidation.docx
Markus Janssen
 
Congestive Heart failure for pharmacology topic hehe
oceangunnu
 
Webinar: World's Smallest Pacemaker
Scintica Instrumentation
 

java script

  • 2. Syllabus : What we learn? See link - https://prezi.com/view/NNmyKQS4eeL9lz89bQyz/  Javascript basics  Introduction to Node JS (framework to run JS without browser anywhere) • Node JS Modules • NPM • Web Server • File system • Events • Databases • Express JS  Introduction to DJango (quick & easy to develop app with minimum code)  Setup  URL pattern  Forms &Validation Monica Deshmane(H.V.Desai College,Pune) 2
  • 3. chap 1 Java Script Basics 1.1 Java Script data types 1.2 Variables, Functions, Events, Regular Expressions 1.3 Array and Objects in Java Script 1.4 Java Script HTML DOM 1.5 Promises and Callbacks
  • 4. Introduction JavaScript is the scripting language for HTML and understood by the Web. JavaScript is easy to learn. JavaScript is made up of the 3 languages : 1. HTML for look & Feel. 2. CSS to specify the layout or style. 3. JavaScript for Event Handling.
  • 5. The <script> Tag Ex. How to write JS? <script type="text/javascript"> var i = 10; if (i < 5) { // some code } </script>
  • 6. The <script> Tag Attributes of <script> 1. async- script is executed asynchronously (only for external scripts) 2. charset –charset Specifies the character encoding format. 3. defer -Specifies that script is executed when the page has finished parsing 4. src - Specifies the URL of an external script file 5. type - Specifies the media type of the script 6. Lang- To specify which language to use.
  • 7. The <script> Tag in < Body> Script gets executed automatcally when program runs or we can call by function call. <html> <body> <p id=“p1">A Paragraph</p> <Input type="button" onclick="myFunction()“ value=“change”> <script> function myFunction() { document.getElementById(“p1").innerHTML = "Paragraph changed."; } </script> </body> </html>
  • 8. The <script> Tag in < Head> The function must be invoked (called) when event occurs . Ex. button is clicked: <html> <head> <script> function myFunction() { document.getElementById(“p1").innerHTML = "Paragraph changed."; } </script></head> <body> <p id=“p1">A Paragraph</p> <Input type="button" onclick="myFunction()">Try it</Input> </body></html> https://www.w3schools.com/js/tryit.asp?filename=tryjs_intro_inner_html
  • 9. Java Script data types 1) String var Name = “parth"; // String 2) Number var length = 36; // Number 3) Boolean Booleans can only have two values: true or false. 4) Undefined var x = 5; var y = 5; (x == y) // Returns true typeof (3) // Returns "number" to return data type of variable typeof undefined // undefined monica Deshmane(H.V.Desai College,Pune) 1) Primitaive data type
  • 10. Java Script data types 1) Function function myFunction() { } 2) Object var x = {firstName:"John", lastName:“Ray"}; // Object 3) Array var cars = [“suzuki", "VagonR", "BMW"]; //array var person = null; //null //diffrence between null & undefined 1) typeof undefined // undefined typeof null // object 2) null === undefined // false null == undefined // true monica Deshmane(H.V.Desai College,Pune) 2)complex data types
  • 11. JS Types:Revise You can divide JavaScript types into 2 groups 1) primitive - are number, Boolean, string, null 2) complex -are array ,functions ,and objects //primitive Var A=5; Var B=A; B=6; A; //5 B; //6 //complex or reference types Var A=[2,3]; Var B=A; B[0]=3; A[0]; //3 B[0]; //3
  • 12. JavaScript variables are used for storing data values. Same rules of variables in java are followed. var x = 5; var y = 6; var z = x + y; also learn- local variables, global variables, static variables Java Script variables monica Deshmane(H.V.Desai College,Pune)
  • 13. A JavaScript function is a block of code to perform a particular task. executed when someone invokes / calls it. Syntax:- function name(para1, para2, para3) { // code to be executed } Java Script Functions monica Deshmane(H.V.Desai College,Pune)
  • 14. Function Invocation i.e call needed. Return value- Functions often compute a return value. The return value is "returned" back to the "caller". Example- var x = myFunction(10, 3); // Function is called, return value will assigned to x function myFunction(a, b) { return a * b; // Function returns the product of a and b } Java Script Functions monica Deshmane(H.V.Desai College,Pune)
  • 15. var f=function f() { typeof f== “function”; //true window==this; //true //as this is global object } .call & .apply method-To change reference of this to any other object when calling function. function a() {this.a==‘b’; //true} funcation a(b,c){ b==‘first’; //true c==‘second’; //true } a.call((a:’b’),’first’,’second’); //call takes list of parameters to pass function a.apply({a:’b’},[’first’,’second’]); //apply takes array of parameters to pass function monica Deshmane(H.V.Desai College,Pune) Some concepts about function..
  • 16. Java Script Events Event Description onChange An HTML element has been changed onClick The user clicks an HTML element / control onMouseOver The user moves the mouse over an HTML element onMouseOut The user moves the mouse away from an HTML element onKeydown The hits pushes a keyboard key onLoad After loading the page onFocus When perticular control is hilighted See demo online monica Deshmane(H.V.Desai College,Pune)
  • 17. •e.g. •<button onclick="displayDate()“>The time is?</button> <body onload=“display()”>….</body> <input type=text name=“txt” onmouseover = “display()”> <input type=text name=“txt” onFocus = “display()”> Examples of events
  • 18. Regular Expressions( RE) monica Deshmane(H.V.Desai College,Pune) A regular expression is a sequence of characters that forms a pattern. The pattern can be used for 1)search 2)replace 3)Match A regular expression can be made by a single character, or a more complicated /mixed patterns.
  • 19. Patterns Character classes [:alum:] Alphanumeric characters [0-9a-zA-Z] [:alpha:] Alphabetic characters [a-zA-Z] [:blank:] space and tab [ t] [:digit:] Digits [0-9] [:lower:] Lower case letters [a-z] [:upper:] Uppercase letters [A-Z] [:xdigit:] Hexadecimal digit [0-9a-fA-F] range of characters ex. [‘aeiou’]
  • 20. Patterns continue… ? 0 or 1 * 0 or more + 1 or more {n} Exactly n times {n,m} Atleast n, no more than m times {n,} Atleast n times n newline t tab ^ beginning $ end
  • 21. Using String Methods monica Deshmane(H.V.Desai College,Pune) the two string methods used for RE are search() and replace(). 1. The search() method uses an expression to search for a match, and returns the position of the match. var pos = str.search(“/this/”); 2. The replace() method returns a modified string where the pattern is replaced. var txt = str.replace(“/is/”, “this"); 3. match() used to match pattern “hi234”.match(/^ (a-z) +(d{3})$/) 4. exec() -Syntax- pattern.exec(string); The exec() method returns the matched text if it finds a match, otherwise it returns null. “/(hey|ho)/”.exec('h') //h
  • 22. Array in Java Script monica Deshmane(H.V.Desai College,Pune) 1. Array creation • var arr1 = new Array(); OR • var arr2 = [ ]; arr2.push(1); arr2.push(2); //[1,2] arr1.sort(); • var arr3 = [ ‘mat', 'rat', 'bat' ]; 2. Length arr2.length; console.log(arr2); 3. To delete element from array arr3.splice(2, 2); arr.pop(); //see demo on JS.do
  • 23. Array splice in Java Script monica Deshmane(H.V.Desai College,Pune) <script> var lang = ["HTML", "CSS", "JS", "Bootstrap"]; document.write(lang + "<br>"); var removed = lang.splice(2, 1, 'PHP', ‘python') document.write(lang + "<br>"); // HTML,CSS,JS,Bootstrap document.write(removed + "<br>"); // HTML,CSS,PHP,python,Bootstrap // No Removing only Insertion from 2nd index from the ending lang.splice(-2, 0, 'React') // JS document.write(lang) // HTML,CSS,PHP,React,python,Bootstrap </script>
  • 24. Array continue… monica Deshmane(H.V.Desai College,Pune) Array is like u so before the typeof operator will return “object” for arrays more times however you want to check that array is actually an array. Array.isArray returns true for arrays and False for any other values. Array.isArray( new array) // true Array.isArray( [ ] ) // true Array.isArray( null) // false Array.isArray(arguments ) //false
  • 25. Array continue… monica Deshmane(H.V.Desai College,Pune) See –tutorials point javascript arrays array methods • to loop over an array you can use for each (Similar to jquery $.each) [1,2,3].foreach(function value) { console.log (value ); } •To filter elements out of array you can use filter (similar two jQuery grep) [1,2,3].foreach(function value) { return value < 3; } //will return [ 1, 2] •to change value of of each item you can use map (similar to Jquery map) [ 5,10 ,15].map function (value) { return value*2; } // will return [10 ,20 ,30] • also available but less commonly used are the methods- reduce , reduceRight and lastIndexOf.
  • 26. Array continue… monica Deshmane(H.V.Desai College,Pune) •reduceRight:-Subtract the numbers in the array, starting from the right: <script> var numberarr= [175, 50, 25]; document.getElementById(“p1").innerHTML = numberarr.reduceRight(myFunc); function myFunc(total, num) { return total - num; } •Reduce-from left to right •lastIndexOf- const animals = ['Dog', 'Tiger', 'Penguin','Dog']; console.log(animals.lastIndexOf('Dog'));// expected output: 3 console.log(animals.lastIndexOf('Tiger'));// expected output: 1
  • 27. •Object Creation var obj1 = new Object(); var obj2 = { }; var subject = { first_name: "HTML", last_name: "CSS“ , reference: 320 ,website: "java2s.com" }; •add a new property subject.name= "brown"; OR subject["name"] = "brown"; •To delete a new property delete subject.name; •To get all keys from object var obj={a:’aaa’, b:’bbb’ ,c:’ccc’}; Object.keys(obj); //[‘a’ ,’b’, ‘c’] Objects in Java Script
  • 29. The HTML DOM is a standard object model and programming interface for HTML. It contains -The HTML elements as objects -The properties of all HTML elements -The methods to access all HTML elements -The events for all HTML elements DOM CSS- The HTML DOM allows JavaScript to change the style of HTML elements. DOM Animation- create HTML animations using JavaScript DOM Events- allows JavaScript to react to HTML events by event handlers & event Listeners. HTML DOM elements are treated as nodes ,in which elements can be added by createElement() or appendChild() & deleted nodes using remove() or removeChild(). HTML DOM continue…
  • 30. Promises & callback - The promises in Javascript are just that, promises it means that we will do everything possible to achieve the expected result. But, we also know that a promise cannot always be fulfilled for some reason. Just as a promise is in real life, it is in Javascript, represented in another way.
  • 31. Promises Example let promise = new Promise(function(resolve, reject) { // task to accomplish your promise if(/* everything turned out fine */) { resolve('Stuff worked') } else { // for some reason the promise doesn't fulfilled reject(new Error('it broke')) } }); Promises have three unique states: 1. Pending: asynchronous operation has not been completed yet. 2. Fulfilled: operation has completed and returns a value. 3. Rejected: The asynchronous operation fails and the reason why it failed is indicated.
  • 32. Callback function will be executed when an asynchronous operation has been completed. A callback is passed as an argument to an asynchronous operation. Normally, this is passed as the last argument of the function. When a function simply accepts another function as an argument, this contained function is known as a callback function. Callback functions are written like : function sayHello() { console.log('Hello everyone');} setTimeout( sayHello( ), 3000); What we did in the above example was, first to define a function that prints a message to the console. After that, we use a timer called setTimeout (this timer is a native Javascript function). This timer is an asynchronous operation that executes the callback after a certain time. In this example, after 3000ms (3 seconds) will be executed the sayHello() function.
  • 33. Difference between callback and promises 1. promises are easy for running asynchronous tasks to feel like synchronous and also provide catching mechanism which are not in callbacks. 2. Promises are built over callbacks. 3. Promises are a very mighty abstraction, allow clean and better code with less errors. 4. In promises, we attach callbacks on the returned promise object. For callback approach, we normally just pass a callback into a function that would then get called upon completion in order to get the result of something. .