5- Javascript Basics
5- Javascript Basics
Web Engineering
1 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
2 / 46
Introduction to JavaScript
JavaScript (JS) is an object-oriented programming language that is
used in conjunction with HTML and CSS to add interactivity to a
website. Some properties are:
• lightweight interpreted (or just-in-time compiled)
programming language
• first-class functions.
• prototype-based,
• single-threaded
• dynamic language
◦ run-time object construction
◦ variable parameter lists,
• multi-paradigm
◦ object-oriented programming
◦ imperative programming
◦ declarative programming
3 / 46
Introduction to JavaScript
• A JavaScript interpreter is embedded in a browser,
◦ Add ability to create dynamic web pages.
◦ JavaScript code acts on the document object model that
the web browser generates.
4 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
5 / 46
Data Types
Two categories
• Primitive data types.
• Composite data types.
6 / 46
Primitive Data Types
• There are five primitive data types associated with five
primitive values. Primitive values are:
◦ Number: represents integers, floats, NAN and infinity.
◦ String: delimited by single or double quotation marks.
◦ Boolean: true or false.
◦ Null: denotes explicitly absence of a value.
◦ Undefined: indicates an uninitialized variable.
• Primitive values have no properties or methods.
• All other non-primitive data types are objects.
7 / 46
Wrapper Objects
The primitive types, number, string and Boolean can be wrapped
by their object counterparts, called wrapper objects.
• Objects
1 var my_obj = {
2 name : " Ayesha " ,
3 age : 25 ,
4 city : " Lahore "
5 };
9 / 46
Variables
Declaration of a variable
• var: function level scope.
• let: block level scope.
• const: block level scope having constant value.
JavaScript is dynamically typed language.
• The data type is determined dynamically at runtime based on
the value you assigned to the variable.
Variables are case-sensitive.
10 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
11 / 46
Conditional Statements
• If...else..
1 let age = 25;
2 if ( age < 18) {
3 console . log ( " You are a minor . " ) ;
4 }
5 else {
6 console . log ( " You are an adult . " ) ;
7 }
12 / 46
Conditional Statements
• switch case...
1 let day = " Monday " ;
2 switch ( day ) {
3 case " Monday " :
4 console . log ( " It ’s the start of the workweek . " ) ;
5 break ;
6 case " Firday " :
7 console . log ( " It ’s almost the weekend ! " ) ;
8 break ;
9 default :
10 console . log ( " It ’s a regular day . " ) ;
11 }
13 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
14 / 46
Loops
• for loop
1 for ( let i = 0; i < 100; i ++) {
2 console . log ( i ) ;
3 }
• for...of loop
1 const cats = [ " Leopard " , " Serval " , " Jaguar " , "
Tiger " , " Caracal " , " Lion " ];
2
3 for ( const cat of cats ) {
4 console . log ( cat ) ;
5 }
15 / 46
Loops
• map() loop: to do something to each item in a collection and
create a new collection containing the changed items:
1 function toUpper ( string ) {
2 return string . toUpperCase () ;
3 }
4
5 const cats = [ " Leopard " , " Serval " , " Jaguar " , "
Tiger " , " Caracal " , " Lion " ];
6
7 const upperCats = cats . map ( toUpper ) ;
8
9 console . log ( upperCats ) ;
10 // [ " LEOPARD " , " SERVAL " , " JAGUAR " , " TIGER " , "
CARACAL " , " LION " ]
16 / 46
Loops
• filter() loop: to test each item in a collection, and create a
new collection containing only items that match:
1 function lCat ( cat ) {
2 return cat . startsWith ( " L " ) ;
3 }
4
5 const cats = [ " Leopard " , " Serval " , " Jaguar " , "
Tiger " , " Caracal " , " Lion " ];
6
7 const filtered = cats . filter ( lCat ) ;
8 console . log ( filtered ) ; // [ " Leopard " , " Lion " ]
Note that map() and filter() are both often used with function
expressions
1 const cats = [ " Leopard " , " Serval " , " Jaguar " , " Tiger " ,
" Caracal " , " Lion " ];
2
3 const filtered = cats . filter (( cat ) = > cat . startsWith ( "
L"));
4 console . log ( filtered ) ; // [ " Leopard " , " Lion " ]
17 / 46
Loop
• while loop
1 initializer
2 while ( condition ) {
3 // code to run
4
5 final - expression
6 }
• do...while loop
1 initializer
2 do {
3 // code to run
4
5 final - expression
6 } while ( condition )
18 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
19 / 46
Functions
• Built-in functions
1 const myArray = [ " I " , " love " , " chocolate " , " frogs "
];
2 const madeAString = myArray . join ( " " ) ;
3 console . log ( madeAString ) ;
• Custom functions
1 function myFunction () {
2 alert ( " hello " ) ;
3 }
4
5 myFunction () ;
• Anonymous functions
1 ( function () {
2 alert ( " hello " ) ;
3 }) ;
If the function only takes one parameter, you can omit the
parentheses around the parameter. If your function contains
only one line that’s a return statement, you can also omit the
braces and the return keyword and implicitly return the
expression.
1 const originals = [1 , 2 , 3];
2 const doubled = originals . map ( item = > item * 2) ;
3 console . log ( doubled ) ; // [2 , 4 , 6]
21 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
22 / 46
JavaScript Objects
Syntax:
1 const objectName = {
2 member1Name : member1Value ,
3 member2Name : member2Value ,
4 member3Name : member3Value ,
5 };
Example:
1 var person = {
2 name : [ " Tauseef " , " Iftikhar " ]
3 age : 45 ,
4 city : " Lahore " ,
5 fullName : function () {
6 return this . name [0] + " " + this . name [1];
7 },
8 introduceSelf : function () {
9 console . log ( " Hello , my name is " + this . fullName ()
+ " and I am " + this . age + " years old . " ) ;}
10 };
An object like this is referred to as an object literal.
23 / 46
JavaScript Objects
Dot notation: we access the object’s properties and methods using
dot notation
1 person . name [0]; \\ Tauseef
2 person . fullName () ;
24 / 46
JavaScript Objects
The dot notation is preferred over the bracket notation, but in
some situations bracket notation is the only solution. For Example:
1 const person = {
2 name : [ " Tauseef " , " Iftikhar " ] ,
3 age : 45 ,
4 };
5
6 function logProperty ( propertyName ) {
7 console . log ( person [ propertyName ]) ;
8 }
9
10 logProperty ( " name " ) ; // [" Tauseef " , " Iftikhar "]
11 logProperty ( " age " ) ; // 45
25 / 46
JavaScript Objects
Setting object members:
1 person . name . first = " Ali "
The bracket notation can be used to set not only member values
dynamically, but member names too.
1 const myDataName = nameInput . value ;
2 const myDataValue = nameValue . value ;
3
4 person [ myDataName ] = myDataValue ;
Example:
1 const myDataName = " height " ;
2 const myDataValue = " 1.75 m " ;
3 person [ myDataName ] = myDataValue ;
4
5 person . height ; \\1.75 m
How will you create more than one objects of the same kind e.g.
person?
26 / 46
JavaScript Objects
One way to create more than one objects of the same type is to
create a function.
1 function createPerson ( name ) {
2 const obj = {};
3 obj . name = name ;
4 obj . introduceSelf = function () {
5 console . log ( ‘ Hi ! I ’m $ { this . name }. ‘) ;
6 };
7 return obj ;
8 }
It works fine but a little bit long-winded. The better way is to use
a constructor.
27 / 46
JavaScript Objects
Constructors: are useful to create more than one objects of the
same type.
1 function Person ( name ) {
2 this . name = name ;
3 this . introduceSelf = function () {
4 console . log ( ‘ Hi ! I ’m $ { this . name }. ‘) ;
5 };
6 }
28 / 46
Synchronous Programming
In synchronous programming, tasks are executed sequentially, with
each operation waiting for the previous one to complete before
proceeding.
1 function makeGreeting ( name ) {
2 return ‘ Hello , my name is $ { name }! ‘;
3 }
4
5 const name = " Ayesha " ;
6 const greeting = makeGreeting ( name ) ;
7 console . log ( greeting ) ;
8 // " Hello , my name is Ayesha !"
29 / 46
Asynchronous Programming
Asynchronous programming is a technique that enables your
program to start a potentially long-running task and still be able to
be responsive to other events while that task runs, rather than
having to wait until that task has finished.
In JavaScript asynchronous programming can be achieved through:
1 Callback function,
2 Promises,
3 async/await.
30 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
31 / 46
Callbacks
A callback is just a function that’s passed into another function.
1 // function
2 function greet ( name , callback ) {
3 console . log ( ’ Hi ’ + ’ ’ + name ) ;
4 callback () ;
5 }
6
7 // callback function
8 function callMe () {
9 console . log ( ’I am a callback function ’) ;
10 }
11
12 // passing function as an argument
13 greet ( ’ Tauseef ’ , callMe ) ;
The benefit of using a callback function is that you can wait for
the result of a previous function call and then execute another
function call.
32 / 46
Callbacks for Asynchronous Programming
1 function greet ( name ) {
2 console . log ( ‘ Hello , $ { name }! ‘) ;
3 }
4
5 // callback function
6 setTimeout ( greet , 2000 , " Ali " ) ;
7 greet ( " Tauseef " ) ;
33 / 46
Nested Callbacks
Nested callbacks
1 function greet ( name , myFunction ) {
2 console . log ( ’ Hello world ’) ;
3
4 myFunction ( name ) ;
5 }
6
7 // callback function
8 function sayName ( name ) {
9 console . log ( ’ Hello ’ + ’ ’ + name ) ;
10 }
11
12 // calling the function after 2 seconds
13 setTimeout ( greet , 2000 , ’ Tauseef ’ , sayName ) ;
14 sayName ( " Ali " )
34 / 46
Problem with Callbacks
1 function doStep1 ( init ) {
2 return init + 1;
3 }
4
5 function doStep2 ( init ) {
6 return init + 2;
7 }
8
9 function doStep3 ( init ) {
10 return init + 3;
11 }
12
13 function doOperation () {
14 let result = 0;
15 result = doStep1 ( result ) ;
16 result = doStep2 ( result ) ;
17 result = doStep3 ( result ) ;
18 console . log ( ‘ result : $ { result } ‘) ;
19 }
20
21 doOperation () ;
35 / 46
Problem with Callbacks
1 function doStep1 ( init , callback ) {
2 const result = init + 1;
3 callback ( result ) ;
4 }
5 function doStep2 ( init , callback ) {
6 const result = init + 2;
7 callback ( result ) ;
8 }
9 function doStep3 ( init , callback ) {
10 const result = init + 3;
11 callback ( result ) ;
12 }
13 function doOperation () {
14 doStep1 (0 , ( result1 ) = > {
15 doStep2 ( result1 , ( result2 ) = > {
16 doStep3 ( result2 , ( result3 ) = > {
17 console . log ( ‘ result : $ { result3 } ‘) ;
18 }) ;
19 }) ;
20 }) ;
21 }
36 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
37 / 46
Promises
• A Promise in JavaScript is an object that represents the
eventual completion or failure of an asynchronous operation.
• A Promise can be in one of the following states:
◦ Pending: Initial state, neither resolved nor rejected.
◦ Fulfilled: The operation was successful.
◦ Rejected: The operation failed.
• A Promise is created using the new Promise constructor,
which takes a function with two parameters:
1 resolve(): Call this when the task is successful.
2 reject(): Call this when the task fails.
38 / 46
Promises
1 const myPromise = new Promise (( resolve , reject ) = >
{
2 let success = true ;
3
4 if ( success ) {
5 resolve ( " Task completed ! " ) ;
6 } else {
7 reject ( " Task failed ! " ) ;
8 }
9 }) ;
10
11 myPromise
12 . then (( message ) = > {
13 console . log ( " Success : " , message ) ;
14 })
15 . catch (( error ) = > {
16 console . log ( " Error : " , error ) ;
17 }) ;
39 / 46
Promises
1 function doStep1 ( init ) {
2 return new Promise (( resolve ) = > {
3 const result = init + 1;
4 resolve ( result ) ;
5 }) ;
6 }
7
8 function doStep2 ( init ) {
9 return new Promise (( resolve ) = > {
10 const result = init + 2;
11 resolve ( result ) ;
12 }) ;
13 }
14
15 function doStep3 ( init ) {
16 return new Promise (( resolve ) = > {
17 const result = init + 3;
18 resolve ( result ) ;
19 }) ;
20 }
40 / 46
Promises
21 function doOperation () {
22 doStep1 (0)
23 . then (( result1 ) = > doStep2 ( result1 ) )
24 . then (( result2 ) = > doStep3 ( result2 ) )
25 . then (( result3 ) = > {
26 console . log ( ‘ result : $ { result3 } ‘) ;
27 })
28 . catch (( error ) = > {
29 console . error ( " Error : " , error ) ;
30 }) ;
31 }
32
33 doOperation () ;
41 / 46
Today’s Agenda
Introduction to JavaScript
Data types and variables
Control flow
Loops
Functions
JavaScript objects
Asynchronous Programming
Callbacks
Promises
async/await
42 / 46
async/await
async/await is a modern way to handle asynchronous operations in
JavaScript. It makes asynchronous code look synchronous,
improving readability and maintainability.
1 async function:
• Declares that the function will return a Promise.
• Inside an async function, you can use await to pause
execution until a Promise resolves.
2 await keyword
• Used inside an async function.
• It waits for the Promise to resolve before proceeding to
the next line.
43 / 46
async/await
Example without async/await
1 function fetchData () {
2 return new Promise (( resolve ) = > {
3 setTimeout (() = > resolve ( " Data received ! " ) ,
2000) ;
4 }) ;
5 }
6
7 fetchData () . then (( data ) = > {
8 console . log ( data ) ;
9 }) ;
Example using async/await
1 async function getData () {
2 const data = await fetchData () ; // Wait for
fetchData () to resolve
3 console . log ( data ) ;
4 }
5
6 getData () ;
44 / 46
async/await
1 function doStep1 ( init ) {
2 return new Promise (( resolve ) = > {
3 const result = init + 1;
4 resolve ( result ) ;
5 }) ;
6 }
7
8 function doStep2 ( init ) {
9 return new Promise (( resolve ) = > {
10 const result = init + 2;
11 resolve ( result ) ;
12 }) ;
13 }
14
15 function doStep3 ( init ) {
16 return new Promise (( resolve ) = > {
17 const result = init + 3;
18 resolve ( result ) ;
19 }) ;
20 }
45 / 46
async/await
21 async function doOperation () {
22 try {
23 const result1 = await doStep1 (0) ; // Wait for
doStep1 to complete
24 const result2 = await doStep2 ( result1 ) ; //
Wait for doStep2 to complete
25 const result3 = await doStep3 ( result2 ) ; //
Wait for doStep3 to complete
26 console . log ( ‘ result : $ { result3 } ‘) ;
27 } catch ( error ) {
28 console . error ( " Error : " , error ) ;
29 }
30 }
31
32 doOperation () ;
46 / 46