SlideShare a Scribd company logo
1 of 17
Download to read offline
LAB Assignments – JavaScript 2022
JavaScript 1
let scope
1. let scope is similar to var.
function letDemo(){
let age=25;
if(new Date().getFullYear()==2017){
age=32;
console.log(age);
}
console.log(age);
}
2. Unlike var, you cannot define the same let variable more than once inside a block:
function letDemo(){
let myage = 39
let myname = 'India'
let myage = 40 // SyntaxError: Identifier myage has
already been declared
}
Note :this will show error myage already declared.
3. let is block scoped, which just means it’s available inside the block (curly braces) it’s
defined in (including inner blocks), but not outside it:
function letDemo(){
if (true){ // new block
let myname = 'India'
}
console.log(myname) // syntax error, myname is
undefined
}
LAB Assignments – JavaScript 2022
JavaScript 2
4. Defining multiple let variables with the same name
function letDemo(){
let mybrother = 'Paul'
if (true){ // new block
let mybrother = 'Jason'
console.log(mybrother) // Jason
}
console.log(mybrother) // Paul
}
5. Using let inside for(...) loops
function greet(){
alert('hello');
}
function letDemo(){
/*for (var i = 0; i < 5; i++){
setTimeout(function(){
console.log(i)
}, i * 100)
}
//logs '5, 5, 5, 5, 5'
*/
/*for (var i = 0; i < 5; i++){
(function(x){
setTimeout(function(){
console.log(x)
}, i * 100)
})(i)
}
//logs '0, 1, 2, 3, 4'
//this is IIFE inside
*/
for (let i = 0; i < 5; i++){
setTimeout(function(){
LAB Assignments – JavaScript 2022
JavaScript 3
Note: This is helpful in many scenarios, such as Ajax requests inside loops that rely on the
value of i to make different requests, or event handlers that utilize the value of i to
perform an action tailored to the element it’s bound to.
Example for Let:
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>MyApplication Demo</title>
<script type="text/javascript" src="script/demo.js"></script>
</head>
<body>
<a href="#" onclick="letExample()">Home</a><br>
<a href="#" onclick="letExample()">Employee </a><br>
<a href="#" onclick="letExample()">Customer</a><br>
<a href="#" onclick="letExample()">Feedbacks</a><br>
<a href="#" onclick="letExample()">Contact Us</a><br>
<a href="#" onclick="letExample()">Click here</a><br>
</body>
</html>
demo.js
function letExample(){
let links = document.getElementsByTagName('a')
for (let i=0; i<links.length; i++){
links[i].onclick = function(){
console.log(i)
}, i * 100)
}
//logs '0, 1, 2, 3, 4'
}
LAB Assignments – JavaScript 2022
JavaScript 4
6. let variables and the Temporal Dead Zone
It is a term in the programming world called the Temporal Dead Zone, and it has
nothing to do with zombies or time shifting, sadly.
alert('You clicked on link ' + (i+1))
}
}
}
function test(){
console.log(dog) // returns ReferenceError
let dog = 'spotty'
}
function test(){
console.log(dog) // returns undefined
var dog = 'spotty' // variable auto hoisted to the
very top of the function (but not its value)
console.log(dog) // ‘spotty’
}
LAB Assignments – JavaScript 2022
JavaScript 5
const scope
1. const variable must be initialized
2. While a const variable cannot be reassigned entirely to a different value, if the value of
a const is an object or array, the object’s properties themselves are still mutable, able to
be modified:
function test(){
const mydog = 'spotty' // good
mydog = 'fluffy' // error: assignment to constant
const mybrother; // error: Missing initializer in
const
}
function test(){
const myobject = {name:'George', age:39}
//myobject = {name: 'Ken', age:39} //error
myobject.age = 40 // OK
const myarray = []
myarray[0] = 'Football' // OK
}
LAB Assignments – JavaScript 2022
JavaScript 6
Arrow function
• JavaScript arrow functions are anonymous functions
• Arrow functions cannot be used as constructor functions, (ie: with the keyword new)
• Lexical binding of this inside arrow function: The value of this inside an arrow function
always points to the same this object of the scope the function is defined in, and never
changes.
LAB Assignments – JavaScript 2022
JavaScript 7
The syntax for JavaScript arrow functions is very easy to remember with the following rules:
• For arrow functions with a single parameter, you can omit the parenthesis () around the
parameter.
• For arrow functions with no or multiple parameters, wrap the parameters in
parenthesis.
• For arrow functions with a single BODY statement, you can omit the braces {} around
the statement. The value derived from the statement is automatically returned with no
braces.
• For arrow functions with multiple BODY statements, wrap them in curly braces. No
value is automatically returned with braces- use the return statement to specify the
value.
• If a function BODY contains only a single object literal, wrap the function BODY in
parenthesis () to differentiate it from the object literal wrapper.
LAB Assignments – JavaScript 2022
JavaScript 8
Syntax
Promises
The then() and catch() methods
Whenever you instantiate a Promise object, two methods- then() and catch()- become
available to decide what happens next after the conclusion of an asynchronous task. Take a
look at the below:
var mypromise = new Promise(function(resolve, reject){
// asynchronous code to run here
// call resolve() to indicate task successfully completed
// call reject() to indicate task has failed
})
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
// alert(img.src);
//document.getElementById('img1').src=url;
})
}
LAB Assignments – JavaScript 2022
JavaScript 9
Example
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' +
successurl + '" />'
})
<!DOCTYPE html>
<html>
<head>
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
}
img.src = url
// alert(img.src);
//document.getElementById('img1').src=url;
})
}
function testPromise(){
getImage('micky1.png').then(
function(successurl){
document.getElementById('cnt').innerHTML = '<img
src="' + successurl + '" />'
},
function(errorurl){
console.log('Error loading ' + errorurl)
}
)
}
LAB Assignments – JavaScript 2022
JavaScript 10
Access with catch
<meta charset="ISO-8859-1">
<title>MyApplication Demo</title>
<script type="text/javascript"
src="script/demo.js"></script>
</head>
<body onload="testPromise()">
<div id="cnt">
</div>
</body>
</html>
function testPromise(){
/*getImage('micky1.png').then(
function(successurl){
document.getElementById('cnt').innerHTML = '<img
src="' + successurl + '" />'
},
function(errorurl){
console.log('Error loading ' + errorurl)
}
)*/
getImage('../micky1.png').then(function(successurl){
document.getElementById('cnt').innerHTML = '<img src="' +
successurl + '" />'
}).catch(function(errorurl){
console.log('Error loading ' + errorurl)
})
}
LAB Assignments – JavaScript 2022
JavaScript 11
Calling catch() is equivalent to calling then(undefined, function), so the above is the same as:
Example
getImage('doggy.jpg').then(function(successurl){
document.getElementById('doggyplayground').innerHTML = '<img src="' +
successurl + '" />'
}).then(undefined, function(errorurl){
console.log('Error loading ' + errorurl)
})
<!DOCTYPE html>
<html>
<head>
<meta charset="ISO-8859-1">
<title>Insert title here</title>
<script type="text/javascript"
src="script/promiseDemo.js"></script>
<style type="text/css">
.demoarea{
border:2px solid darkbrown;
padding:5px;
.demoarea img{
margin-right: 10px;
</style>
</head>
<body >
<div id="doggyplayground" class="demoarea">
</div>
LAB Assignments – JavaScript 2022
JavaScript 12
<button onclick="demo1()">show</button>
</body>
</html>
promiseDemo.js
function displayimages(images){
var doggyplayground =
document.getElementById('doggyplayground');
var targetimage = images.shift(); // process doggies images
one at a time
if (targetimage){ // if not end of array
getImage(targetimage).then(function(url){ // load image
then...
var dog = document.createElement('img')
dog.setAttribute('src', url)
doggyplayground.appendChild(dog) // add image to DIV
displayimages(images) // recursion- call
displayimages() again to process next image/doggy
}).catch(function(url){ // handle an image not loading
console.log('Error loading ' + url)
displayimages(images) // recursion- call
displayimages() again to process next image/doggy
})
}
}
function getImage(url){
return new Promise(function(resolve, reject){
var img = new Image()
img.onload = function(){
resolve(url)
}
img.onerror = function(){
reject(url)
LAB Assignments – JavaScript 2022
JavaScript 13
img.src = url
// alert(img.src);
//document.getElementById('img1').src=url;
})
function demo1(){
var doggies = ['dog1.png', 'dog2.png', 'dog3.png',
'dog4.png', 'dog5.png']
//doggyplayground.innerHTML = ''
displayimages(doggies)
LAB Assignments – JavaScript 2022
JavaScript 14
Async Functions
The Anatomy of an Async Function
Async functions are defined by placing the async keyword in front of a function, such as:
This does two things:
• It causes the function to always return a promise whether or not you explicitly return
something, so you can call then() on it for example. More on this later.
• It allows you to use the await keyword inside it to wait on a promise until it is resolved
before continuing on to the next line inside the async function.
async fetchdata(url){
// Do something
// Always returns a promise
}
"Async functions always returns a promise. If we explicitly return a value at the end of our
async function, the promise will be resolved with that value; otherwise, it resolves
with undefined."
LAB Assignments – JavaScript 2022
JavaScript 15
Closure
An Example of a Closure
Two one sentence summaries:
• a closure is the local variables for a function - kept alive after the function has returned,
or
• a closure is a stack-frame which is not deallocated when the function returns. (as if a
'stack-frame' were malloc'ed instead of being on the stack!)
function sayHello(name){
var text = 'Hello ' + name;
var sayAlert = function(){ alert(text); }
return sayAlert();
}
LAB Assignments – JavaScript 2022
JavaScript 16
Callback function
var myCallBackExample = {
myFirstFunction : function( param1, param2, callback ) {
// Do something with param1 and param2.
if ( arguments.length == 3 ) {
// Execute callback function.
// What is the "best" way to do this?
}
},
mySecondFunction : function() {
myFirstFunction( false, true, function() {
// When this anonymous function is called, execute it.
});
}
};
LAB Assignments – JavaScript 2022
JavaScript 17
Prototype
The JavaScript prototype property allows you to add new properties to an existing prototype
Note:
Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects.
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.nationality = "English";
function Person(first, last, age, eyecolor) {
this.firstName = first;
this.lastName = last;
this.age = age;
this.eyeColor = eyecolor;
}
Person.prototype.name = function() {
return this.firstName + " " + this.lastName;
};

More Related Content

What's hot

jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...Edureka!
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#Rizwan Ali
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOdoo
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Edureka!
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++rprajat007
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overridingRajab Ali
 
Java Networking
Java NetworkingJava Networking
Java NetworkingSunil OS
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScriptShahDhruv21
 
Abstraction and Encapsulation
Abstraction and EncapsulationAbstraction and Encapsulation
Abstraction and EncapsulationHaris Bin Zahid
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File Harjinder Singh
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action barDiego Grancini
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++Vishesh Jha
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5Gil Fink
 

What's hot (20)

jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
jQuery Tutorial For Beginners | Developing User Interface (UI) Using jQuery |...
 
Threads And Synchronization in C#
Threads And Synchronization in C#Threads And Synchronization in C#
Threads And Synchronization in C#
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
 
Encapsulation C++
Encapsulation C++Encapsulation C++
Encapsulation C++
 
Owl: The New Odoo UI Framework
Owl: The New Odoo UI FrameworkOwl: The New Odoo UI Framework
Owl: The New Odoo UI Framework
 
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
Python Flask Tutorial For Beginners | Flask Web Development Tutorial | Python...
 
Class and object in C++
Class and object in C++Class and object in C++
Class and object in C++
 
Function overloading and overriding
Function overloading and overridingFunction overloading and overriding
Function overloading and overriding
 
Java Networking
Java NetworkingJava Networking
Java Networking
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
 
Abstraction and Encapsulation
Abstraction and EncapsulationAbstraction and Encapsulation
Abstraction and Encapsulation
 
Data Structures Practical File
Data Structures Practical File Data Structures Practical File
Data Structures Practical File
 
Introduction to package in java
Introduction to package in javaIntroduction to package in java
Introduction to package in java
 
Android App Development - 05 Action bar
Android App Development - 05 Action barAndroid App Development - 05 Action bar
Android App Development - 05 Action bar
 
Operator overloading
Operator overloadingOperator overloading
Operator overloading
 
jQuery PPT
jQuery PPTjQuery PPT
jQuery PPT
 
DOM and Events
DOM and EventsDOM and Events
DOM and Events
 
Polymorphism In c++
Polymorphism In c++Polymorphism In c++
Polymorphism In c++
 
Introduction to HTML5
Introduction to HTML5Introduction to HTML5
Introduction to HTML5
 

Similar to Javascript Exercises

jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptGuy Royse
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e bigAndy Peterson
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"GeeksLab Odessa
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-ChallengesJose Mendez
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: FunctionsAdam Crabtree
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-senseBen Lin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPresswpnepal
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascriptmpnkhan
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript Glenn Stovall
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashBret Little
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to JavascriptAnjan Banda
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Searchindeedeng
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing UpDavid Padbury
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponentsMartin Hochel
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of JavascriptTarek Yehia
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHPStephen Young
 

Similar to Javascript Exercises (20)

jQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScriptjQuery & 10,000 Global Functions: Working with Legacy JavaScript
jQuery & 10,000 Global Functions: Working with Legacy JavaScript
 
Javascript unit testing, yes we can e big
Javascript unit testing, yes we can   e bigJavascript unit testing, yes we can   e big
Javascript unit testing, yes we can e big
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
 
React lecture
React lectureReact lecture
React lecture
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
 
Reliable Javascript
Reliable Javascript Reliable Javascript
Reliable Javascript
 
JavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and LodashJavaScript Fundamentals with Angular and Lodash
JavaScript Fundamentals with Angular and Lodash
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
 

More from SRINIVAS KOLAPARTHI

More from SRINIVAS KOLAPARTHI (6)

Salesforce Lightning Message Service.pdf
Salesforce Lightning Message Service.pdfSalesforce Lightning Message Service.pdf
Salesforce Lightning Message Service.pdf
 
JavaScript Object API
JavaScript Object APIJavaScript Object API
JavaScript Object API
 
Service Discovery in MicroServices
Service Discovery in MicroServicesService Discovery in MicroServices
Service Discovery in MicroServices
 
Zuul_Intro.pdf
Zuul_Intro.pdfZuul_Intro.pdf
Zuul_Intro.pdf
 
MultiThreading in Python
MultiThreading in PythonMultiThreading in Python
MultiThreading in Python
 
Salesforce LWC Toast Message
Salesforce LWC Toast MessageSalesforce LWC Toast Message
Salesforce LWC Toast Message
 

Recently uploaded

Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksSoftradix Technologies
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Enterprise Knowledge
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentationphoebematthew05
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfngoud9212
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...shyamraj55
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfjimielynbastida
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupFlorian Wilhelm
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfAddepto
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDGMarianaLemus7
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationSlibray Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):comworks
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsRizwan Syed
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machinePadma Pradeep
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebUiPathCommunity
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitecturePixlogix Infotech
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Mark Simos
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024BookNet Canada
 

Recently uploaded (20)

E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptxE-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
E-Vehicle_Hacking_by_Parul Sharma_null_owasp.pptx
 
Benefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other FrameworksBenefits Of Flutter Compared To Other Frameworks
Benefits Of Flutter Compared To Other Frameworks
 
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort ServiceHot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
Hot Sexy call girls in Panjabi Bagh 🔝 9953056974 🔝 Delhi escort Service
 
Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024Designing IA for AI - Information Architecture Conference 2024
Designing IA for AI - Information Architecture Conference 2024
 
costume and set research powerpoint presentation
costume and set research powerpoint presentationcostume and set research powerpoint presentation
costume and set research powerpoint presentation
 
Bluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdfBluetooth Controlled Car with Arduino.pdf
Bluetooth Controlled Car with Arduino.pdf
 
Pigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food ManufacturingPigging Solutions in Pet Food Manufacturing
Pigging Solutions in Pet Food Manufacturing
 
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
Automating Business Process via MuleSoft Composer | Bangalore MuleSoft Meetup...
 
Science&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdfScience&tech:THE INFORMATION AGE STS.pdf
Science&tech:THE INFORMATION AGE STS.pdf
 
Streamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project SetupStreamlining Python Development: A Guide to a Modern Project Setup
Streamlining Python Development: A Guide to a Modern Project Setup
 
Gen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdfGen AI in Business - Global Trends Report 2024.pdf
Gen AI in Business - Global Trends Report 2024.pdf
 
APIForce Zurich 5 April Automation LPDG
APIForce Zurich 5 April  Automation LPDGAPIForce Zurich 5 April  Automation LPDG
APIForce Zurich 5 April Automation LPDG
 
Connect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck PresentationConnect Wave/ connectwave Pitch Deck Presentation
Connect Wave/ connectwave Pitch Deck Presentation
 
CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):CloudStudio User manual (basic edition):
CloudStudio User manual (basic edition):
 
Scanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL CertsScanning the Internet for External Cloud Exposures via SSL Certs
Scanning the Internet for External Cloud Exposures via SSL Certs
 
Install Stable Diffusion in windows machine
Install Stable Diffusion in windows machineInstall Stable Diffusion in windows machine
Install Stable Diffusion in windows machine
 
Dev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio WebDev Dives: Streamline document processing with UiPath Studio Web
Dev Dives: Streamline document processing with UiPath Studio Web
 
Understanding the Laravel MVC Architecture
Understanding the Laravel MVC ArchitectureUnderstanding the Laravel MVC Architecture
Understanding the Laravel MVC Architecture
 
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
Tampa BSides - Chef's Tour of Microsoft Security Adoption Framework (SAF)
 
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
New from BookNet Canada for 2024: BNC BiblioShare - Tech Forum 2024
 

Javascript Exercises

  • 1. LAB Assignments – JavaScript 2022 JavaScript 1 let scope 1. let scope is similar to var. function letDemo(){ let age=25; if(new Date().getFullYear()==2017){ age=32; console.log(age); } console.log(age); } 2. Unlike var, you cannot define the same let variable more than once inside a block: function letDemo(){ let myage = 39 let myname = 'India' let myage = 40 // SyntaxError: Identifier myage has already been declared } Note :this will show error myage already declared. 3. let is block scoped, which just means it’s available inside the block (curly braces) it’s defined in (including inner blocks), but not outside it: function letDemo(){ if (true){ // new block let myname = 'India' } console.log(myname) // syntax error, myname is undefined }
  • 2. LAB Assignments – JavaScript 2022 JavaScript 2 4. Defining multiple let variables with the same name function letDemo(){ let mybrother = 'Paul' if (true){ // new block let mybrother = 'Jason' console.log(mybrother) // Jason } console.log(mybrother) // Paul } 5. Using let inside for(...) loops function greet(){ alert('hello'); } function letDemo(){ /*for (var i = 0; i < 5; i++){ setTimeout(function(){ console.log(i) }, i * 100) } //logs '5, 5, 5, 5, 5' */ /*for (var i = 0; i < 5; i++){ (function(x){ setTimeout(function(){ console.log(x) }, i * 100) })(i) } //logs '0, 1, 2, 3, 4' //this is IIFE inside */ for (let i = 0; i < 5; i++){ setTimeout(function(){
  • 3. LAB Assignments – JavaScript 2022 JavaScript 3 Note: This is helpful in many scenarios, such as Ajax requests inside loops that rely on the value of i to make different requests, or event handlers that utilize the value of i to perform an action tailored to the element it’s bound to. Example for Let: <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>MyApplication Demo</title> <script type="text/javascript" src="script/demo.js"></script> </head> <body> <a href="#" onclick="letExample()">Home</a><br> <a href="#" onclick="letExample()">Employee </a><br> <a href="#" onclick="letExample()">Customer</a><br> <a href="#" onclick="letExample()">Feedbacks</a><br> <a href="#" onclick="letExample()">Contact Us</a><br> <a href="#" onclick="letExample()">Click here</a><br> </body> </html> demo.js function letExample(){ let links = document.getElementsByTagName('a') for (let i=0; i<links.length; i++){ links[i].onclick = function(){ console.log(i) }, i * 100) } //logs '0, 1, 2, 3, 4' }
  • 4. LAB Assignments – JavaScript 2022 JavaScript 4 6. let variables and the Temporal Dead Zone It is a term in the programming world called the Temporal Dead Zone, and it has nothing to do with zombies or time shifting, sadly. alert('You clicked on link ' + (i+1)) } } } function test(){ console.log(dog) // returns ReferenceError let dog = 'spotty' } function test(){ console.log(dog) // returns undefined var dog = 'spotty' // variable auto hoisted to the very top of the function (but not its value) console.log(dog) // ‘spotty’ }
  • 5. LAB Assignments – JavaScript 2022 JavaScript 5 const scope 1. const variable must be initialized 2. While a const variable cannot be reassigned entirely to a different value, if the value of a const is an object or array, the object’s properties themselves are still mutable, able to be modified: function test(){ const mydog = 'spotty' // good mydog = 'fluffy' // error: assignment to constant const mybrother; // error: Missing initializer in const } function test(){ const myobject = {name:'George', age:39} //myobject = {name: 'Ken', age:39} //error myobject.age = 40 // OK const myarray = [] myarray[0] = 'Football' // OK }
  • 6. LAB Assignments – JavaScript 2022 JavaScript 6 Arrow function • JavaScript arrow functions are anonymous functions • Arrow functions cannot be used as constructor functions, (ie: with the keyword new) • Lexical binding of this inside arrow function: The value of this inside an arrow function always points to the same this object of the scope the function is defined in, and never changes.
  • 7. LAB Assignments – JavaScript 2022 JavaScript 7 The syntax for JavaScript arrow functions is very easy to remember with the following rules: • For arrow functions with a single parameter, you can omit the parenthesis () around the parameter. • For arrow functions with no or multiple parameters, wrap the parameters in parenthesis. • For arrow functions with a single BODY statement, you can omit the braces {} around the statement. The value derived from the statement is automatically returned with no braces. • For arrow functions with multiple BODY statements, wrap them in curly braces. No value is automatically returned with braces- use the return statement to specify the value. • If a function BODY contains only a single object literal, wrap the function BODY in parenthesis () to differentiate it from the object literal wrapper.
  • 8. LAB Assignments – JavaScript 2022 JavaScript 8 Syntax Promises The then() and catch() methods Whenever you instantiate a Promise object, two methods- then() and catch()- become available to decide what happens next after the conclusion of an asynchronous task. Take a look at the below: var mypromise = new Promise(function(resolve, reject){ // asynchronous code to run here // call resolve() to indicate task successfully completed // call reject() to indicate task has failed }) function getImage(url){ return new Promise(function(resolve, reject){ var img = new Image() img.onload = function(){ resolve(url) } img.onerror = function(){ reject(url) } img.src = url // alert(img.src); //document.getElementById('img1').src=url; }) }
  • 9. LAB Assignments – JavaScript 2022 JavaScript 9 Example getImage('doggy.jpg').then(function(successurl){ document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />' }) <!DOCTYPE html> <html> <head> function getImage(url){ return new Promise(function(resolve, reject){ var img = new Image() img.onload = function(){ resolve(url) } img.onerror = function(){ reject(url) } img.src = url // alert(img.src); //document.getElementById('img1').src=url; }) } function testPromise(){ getImage('micky1.png').then( function(successurl){ document.getElementById('cnt').innerHTML = '<img src="' + successurl + '" />' }, function(errorurl){ console.log('Error loading ' + errorurl) } ) }
  • 10. LAB Assignments – JavaScript 2022 JavaScript 10 Access with catch <meta charset="ISO-8859-1"> <title>MyApplication Demo</title> <script type="text/javascript" src="script/demo.js"></script> </head> <body onload="testPromise()"> <div id="cnt"> </div> </body> </html> function testPromise(){ /*getImage('micky1.png').then( function(successurl){ document.getElementById('cnt').innerHTML = '<img src="' + successurl + '" />' }, function(errorurl){ console.log('Error loading ' + errorurl) } )*/ getImage('../micky1.png').then(function(successurl){ document.getElementById('cnt').innerHTML = '<img src="' + successurl + '" />' }).catch(function(errorurl){ console.log('Error loading ' + errorurl) }) }
  • 11. LAB Assignments – JavaScript 2022 JavaScript 11 Calling catch() is equivalent to calling then(undefined, function), so the above is the same as: Example getImage('doggy.jpg').then(function(successurl){ document.getElementById('doggyplayground').innerHTML = '<img src="' + successurl + '" />' }).then(undefined, function(errorurl){ console.log('Error loading ' + errorurl) }) <!DOCTYPE html> <html> <head> <meta charset="ISO-8859-1"> <title>Insert title here</title> <script type="text/javascript" src="script/promiseDemo.js"></script> <style type="text/css"> .demoarea{ border:2px solid darkbrown; padding:5px; .demoarea img{ margin-right: 10px; </style> </head> <body > <div id="doggyplayground" class="demoarea"> </div>
  • 12. LAB Assignments – JavaScript 2022 JavaScript 12 <button onclick="demo1()">show</button> </body> </html> promiseDemo.js function displayimages(images){ var doggyplayground = document.getElementById('doggyplayground'); var targetimage = images.shift(); // process doggies images one at a time if (targetimage){ // if not end of array getImage(targetimage).then(function(url){ // load image then... var dog = document.createElement('img') dog.setAttribute('src', url) doggyplayground.appendChild(dog) // add image to DIV displayimages(images) // recursion- call displayimages() again to process next image/doggy }).catch(function(url){ // handle an image not loading console.log('Error loading ' + url) displayimages(images) // recursion- call displayimages() again to process next image/doggy }) } } function getImage(url){ return new Promise(function(resolve, reject){ var img = new Image() img.onload = function(){ resolve(url) } img.onerror = function(){ reject(url)
  • 13. LAB Assignments – JavaScript 2022 JavaScript 13 img.src = url // alert(img.src); //document.getElementById('img1').src=url; }) function demo1(){ var doggies = ['dog1.png', 'dog2.png', 'dog3.png', 'dog4.png', 'dog5.png'] //doggyplayground.innerHTML = '' displayimages(doggies)
  • 14. LAB Assignments – JavaScript 2022 JavaScript 14 Async Functions The Anatomy of an Async Function Async functions are defined by placing the async keyword in front of a function, such as: This does two things: • It causes the function to always return a promise whether or not you explicitly return something, so you can call then() on it for example. More on this later. • It allows you to use the await keyword inside it to wait on a promise until it is resolved before continuing on to the next line inside the async function. async fetchdata(url){ // Do something // Always returns a promise } "Async functions always returns a promise. If we explicitly return a value at the end of our async function, the promise will be resolved with that value; otherwise, it resolves with undefined."
  • 15. LAB Assignments – JavaScript 2022 JavaScript 15 Closure An Example of a Closure Two one sentence summaries: • a closure is the local variables for a function - kept alive after the function has returned, or • a closure is a stack-frame which is not deallocated when the function returns. (as if a 'stack-frame' were malloc'ed instead of being on the stack!) function sayHello(name){ var text = 'Hello ' + name; var sayAlert = function(){ alert(text); } return sayAlert(); }
  • 16. LAB Assignments – JavaScript 2022 JavaScript 16 Callback function var myCallBackExample = { myFirstFunction : function( param1, param2, callback ) { // Do something with param1 and param2. if ( arguments.length == 3 ) { // Execute callback function. // What is the "best" way to do this? } }, mySecondFunction : function() { myFirstFunction( false, true, function() { // When this anonymous function is called, execute it. }); } };
  • 17. LAB Assignments – JavaScript 2022 JavaScript 17 Prototype The JavaScript prototype property allows you to add new properties to an existing prototype Note: Only modify your own prototypes. Never modify the prototypes of standard JavaScript objects. function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.nationality = "English"; function Person(first, last, age, eyecolor) { this.firstName = first; this.lastName = last; this.age = age; this.eyeColor = eyecolor; } Person.prototype.name = function() { return this.firstName + " " + this.lastName; };