SlideShare a Scribd company logo
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;
};
Ad

More Related Content

What's hot (20)

Data controls ppt
Data controls pptData controls ppt
Data controls ppt
Iblesoft
 
CSS
CSS CSS
CSS
Sunil OS
 
Intro to HTML and CSS basics
Intro to HTML and CSS basicsIntro to HTML and CSS basics
Intro to HTML and CSS basics
Eliran Eliassy
 
3. Java Script
3. Java Script3. Java Script
3. Java Script
Jalpesh Vasa
 
C# Inheritance
C# InheritanceC# Inheritance
C# Inheritance
Prem Kumar Badri
 
Lambda Expressions in Java
Lambda Expressions in JavaLambda Expressions in Java
Lambda Expressions in Java
Erhan Bagdemir
 
This keyword in java
This keyword in javaThis keyword in java
This keyword in java
Hitesh Kumar
 
Introduction to JavaScript Basics.
Introduction to JavaScript Basics.Introduction to JavaScript Basics.
Introduction to JavaScript Basics.
Hassan Ahmed Baig - Web Developer
 
JavaScript: Variables and Functions
JavaScript: Variables and FunctionsJavaScript: Variables and Functions
JavaScript: Variables and Functions
Jussi Pohjolainen
 
08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt08 c++ Operator Overloading.ppt
08 c++ Operator Overloading.ppt
Tareq Hasan
 
Oops concepts in php
Oops concepts in phpOops concepts in php
Oops concepts in php
CPD INDIA
 
PHP POWERPOINT SLIDES
PHP POWERPOINT SLIDESPHP POWERPOINT SLIDES
PHP POWERPOINT SLIDES
Ismail Mukiibi
 
CSS3, Media Queries, and Responsive Design
CSS3, Media Queries, and Responsive DesignCSS3, Media Queries, and Responsive Design
CSS3, Media Queries, and Responsive Design
Zoe Gillenwater
 
Bootstrap
BootstrapBootstrap
Bootstrap
AvinashChunduri2
 
PHP
PHPPHP
PHP
Steve Fort
 
Data types in php
Data types in phpData types in php
Data types in php
ilakkiya
 
Php with MYSQL Database
Php with MYSQL DatabasePhp with MYSQL Database
Php with MYSQL Database
Computer Hardware & Trouble shooting
 
jQuery
jQueryjQuery
jQuery
Dileep Mishra
 
Cours JavaScript
Cours JavaScriptCours JavaScript
Cours JavaScript
Olivier Le Goaër
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 

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
Guy 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 big
Andy Peterson
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
Jose Mendez
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
React lecture
React lectureReact lecture
React lecture
Christoffer Noring
 
Oojs 1.1
Oojs 1.1Oojs 1.1
Oojs 1.1
Rodica Dada
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
Ben Lin
 
Clean Javascript
Clean JavascriptClean Javascript
Clean Javascript
Ryunosuke SATO
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
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 Lodash
Bret Little
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
indeedeng
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
Martin Hochel
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
25-functions.ppt
25-functions.ppt25-functions.ppt
25-functions.ppt
JyothiAmpally
 
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
Guy 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 big
Andy Peterson
 
JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"JSLab. Алексей Волков. "React на практике"
JSLab. Алексей Волков. "React на практике"
GeeksLab Odessa
 
Angular Mini-Challenges
Angular Mini-ChallengesAngular Mini-Challenges
Angular Mini-Challenges
Jose Mendez
 
LinkedIn TBC JavaScript 100: Functions
 LinkedIn TBC JavaScript 100: Functions LinkedIn TBC JavaScript 100: Functions
LinkedIn TBC JavaScript 100: Functions
Adam Crabtree
 
Heroku pop-behind-the-sense
Heroku pop-behind-the-senseHeroku pop-behind-the-sense
Heroku pop-behind-the-sense
Ben Lin
 
Avinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPressAvinash Kundaliya: Javascript and WordPress
Avinash Kundaliya: Javascript and WordPress
wpnepal
 
Effecient javascript
Effecient javascriptEffecient javascript
Effecient javascript
mpnkhan
 
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 Lodash
Bret Little
 
Intro to Javascript
Intro to JavascriptIntro to Javascript
Intro to Javascript
Anjan Banda
 
[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search[@IndeedEng] Building Indeed Resume Search
[@IndeedEng] Building Indeed Resume Search
indeedeng
 
JavaScript Growing Up
JavaScript Growing UpJavaScript Growing Up
JavaScript Growing Up
David Padbury
 
Reactive Type-safe WebComponents
Reactive Type-safe WebComponentsReactive Type-safe WebComponents
Reactive Type-safe WebComponents
Martin Hochel
 
Art of Javascript
Art of JavascriptArt of Javascript
Art of Javascript
Tarek Yehia
 
Using RequireJS with CakePHP
Using RequireJS with CakePHPUsing RequireJS with CakePHP
Using RequireJS with CakePHP
Stephen Young
 
Ad

More from SRINIVAS KOLAPARTHI (6)

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

Recently uploaded (20)

Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 
Cyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of securityCyber Awareness overview for 2025 month of security
Cyber Awareness overview for 2025 month of security
riccardosl1
 
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep DiveDesigning Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
Designing Low-Latency Systems with Rust and ScyllaDB: An Architectural Deep Dive
ScyllaDB
 
Semantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AISemantic Cultivators : The Critical Future Role to Enable AI
Semantic Cultivators : The Critical Future Role to Enable AI
artmondano
 
Rusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond SparkRusty Waters: Elevating Lakehouses Beyond Spark
Rusty Waters: Elevating Lakehouses Beyond Spark
carlyakerly1
 
Technology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data AnalyticsTechnology Trends in 2025: AI and Big Data Analytics
Technology Trends in 2025: AI and Big Data Analytics
InData Labs
 
Quantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur MorganQuantum Computing Quick Research Guide by Arthur Morgan
Quantum Computing Quick Research Guide by Arthur Morgan
Arthur Morgan
 
2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx2025-05-Q4-2024-Investor-Presentation.pptx
2025-05-Q4-2024-Investor-Presentation.pptx
Samuele Fogagnolo
 
Drupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy ConsumptionDrupalcamp Finland – Measuring Front-end Energy Consumption
Drupalcamp Finland – Measuring Front-end Energy Consumption
Exove
 
HCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser EnvironmentsHCL Nomad Web – Best Practices and Managing Multiuser Environments
HCL Nomad Web – Best Practices and Managing Multiuser Environments
panagenda
 
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-UmgebungenHCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
HCL Nomad Web – Best Practices und Verwaltung von Multiuser-Umgebungen
panagenda
 
What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...What is Model Context Protocol(MCP) - The new technology for communication bw...
What is Model Context Protocol(MCP) - The new technology for communication bw...
Vishnu Singh Chundawat
 
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
#StandardsGoals for 2025: Standards & certification roundup - Tech Forum 2025
BookNet Canada
 
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Enhancing ICU Intelligence: How Our Functional Testing Enabled a Healthcare I...
Impelsys Inc.
 
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptxDevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
DevOpsDays Atlanta 2025 - Building 10x Development Organizations.pptx
Justin Reock
 
How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?How Can I use the AI Hype in my Business Context?
How Can I use the AI Hype in my Business Context?
Daniel Lehner
 
Procurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptxProcurement Insights Cost To Value Guide.pptx
Procurement Insights Cost To Value Guide.pptx
Jon Hansen
 
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded DevelopersLinux Support for SMARC: How Toradex Empowers Embedded Developers
Linux Support for SMARC: How Toradex Empowers Embedded Developers
Toradex
 
AI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global TrendsAI and Data Privacy in 2025: Global Trends
AI and Data Privacy in 2025: Global Trends
InData Labs
 
Heap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and DeletionHeap, Types of Heap, Insertion and Deletion
Heap, Types of Heap, Insertion and Deletion
Jaydeep Kale
 
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven InsightsAndrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell: Transforming Business Strategy Through Data-Driven Insights
Andrew Marnell
 

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; };