Lecture 3
Introduction to JavaScript
D. Munthali- BSc. I.T, MSc. Prog & Sys Arch
CIT-PRG-321- Script Programming
Outline
• Introduction • Control structures
• History • Functions
• Standardisation • Object Oriented
• Executing JS Programming
• Variables • Creating objects
• Datatypes • Manipulating objects
• Operators • The “this” keyword
Outline
• The call and apply • JS Arrays
methods • JS methods
• Getters and setters
• Static members
• Object methods
• Inheritance
• JSON
Introduction
• JavaScript is an interpreted scripting
language
• The interpreters are embedded in web
browsers, need to install an interpreter.
• The primary purpose is to add
interactivity to web pages
• It can also be used for server-side
scripting using Node.js
History
• It was developed by Brendan Eich at
Netscape (Mozilla Corporation) in 1995
• Developed to add interactivity to
NetScape navigator
• There was lack of standards, there
were independent implementations
• There were inconsistences across
browsers
• See “JavaScript wars” Navigator vs IE
Standardisation
• In 1996, Netscape submitted JavaScript
to the European Computer Manufacturers
Association (ECMA) for standardization
• The first version was ECMA script 1- 1997
• ECMAScript 3- released in 1999
• Regular expressions, try-catch exception
handling..
• ECMAScript 5- released in 2009
• Strict mode, JSON support, improved
array manipulation..
Standardisation
• ECMAScript 6 (ES6) – Released in 2015
• Arrow functions, classes, modules
• In 2016 ECMAScript specification transitioned to
an annual release cycle
• ECMAScript 2017
• ECMAScript 2018
• ECMAScript 2019
• ECMAScript 2020
• ….
• ECMAScript 2023
Adding JS to a page
• Inside the script tag
• Placeable in body and head
• Not recommended- Difficult to maintain
• Will be used for teaching purpose
• Reference to an external file
• Recommended: easy to maintain
Running JS
Running JS
• You can also run JS
using Node.js
• But you cannot
manipulate the DOM
[see in later lectures]
• Convenient when
working basic JS &
backend
Variables
• JS is a loosely typed language
• No explicit data type specification
• There are several ways of
creating variables:
• automatic: name = “Joe Doe”
• using var: var name = “Joe Doe”
• using let: let name = “Joe Doe”
• using const: const PI = 3.14
Variables
• Declaring variable automatically
won’t work in strict mode
• Use const when declaring constants
─ The value & datatype cannot change
─ Const was added in ES6
• Use let to declare standard variables
─ The value & datatype can change
─ Let was added in ES6
• Use the var keyword to support old
browsers- its discouraged!
Data Types
• The following are primitive
data types in JS:
─ number: let a = 23
─ boolean: let status = false
─ undefined: let f
─ string: let u = “hello”
─ null: const car = null
• Object types:
─ Array: const r = [1,2,3]
─ Object: const c = {name:”Joe”}
Variables- take note!
• A variable in JS can hold any data
type
• A const variable cannot be
reassigned, for arrays & objects it
can be changed!
const numbers = [1,2,3]
numbers = [4,5] // not allowed
numbers[0] = 0 // allowed
• All const variables must be
assigned a value
Operators
Arithmetic operators
• These include:
─Addition
─Subtraction
─Division
─Multiplication
─Power [ES6]
─Increment
─Decrement
The “+” operator: take note!
• When working with numbers,
the + operator acts as an
arithmetic operator
• When working with numbers
and/or strings the + operator
works as a concatenator
• What about the other
arithmetic operators?
The “+” operator: take note!
• When working with numbers,
the + operator acts as an
arithmetic operator
• When working with numbers
and/or strings the + operator
works as a concatenator
• What about the other
arithmetic operators?
Comparison operators
• These include:
─Greater than: >
─Less than: <
─Equal to: ==
─Not equal to: !=
─Equal to (value & type): ===
─Greater than or equal to: >=
─Less than or equal to: <=
─Not equal to (value & type: !==
Assignment operators
• These include:
─Assign value to a variable: =
─Add value & assign: +=
─Sub value & assign: -=
─Mult value & assign: *=
─Div value & assign: /=
─Mod value & assign: %=
─Exp value & assign: **=
Logical operators
• These include:
─Logical and: &&
─Logical OR: ||
─Logical not: !
Special operators- condition
• The condition operator
• A simple way of writing
conditional statements
• condition ? expression1 :
expression2
Special operators- condition
• instanceof- check if an
object is an instance of a
class
• typeof- return the type of a
variable
• delete: deletes elements in
array and object properties
• new – it is used to create
objects
Control structures
• JS support similar control
structure to those found in
many programming
languages
• These include:
─ if else
─ switch
─ while loop
─ do while
─ for loop
─ for of
Control structures
• If- executes a block of
statements in which a
condition evaluates to
true
• Else- executes the block
when the condition is
false
• If else- allow chaining of
multiple conditions
Control structures – while loop
• Execute a block of code
until the condition is false
• Do while loop execute
the block ate least once!
─The condition is checked
at the end of the block
• If the condition never
becomes false, it will be
infinite!
─The browser will crash!
Control structures – for loop
▪ Executes a block of code
until the condition is false
▪ It has an initialisation,
condition and counter.
▪ In each iteration the
counter is decremented
or incremented until the
condition becomes false.
Control structures – for.. of loop
▪ For of loop is used to loop
through iterable objects
▪ Iterables are objects that
implement iterable protocol
▪ JS Iterables include:
─ strings
─ Arrays
─ Set
─ Map
Functions
▪ A function is a block of
reusable code that
performs a particular
task
▪ There are many ways of
creating functions in JS,
we are going to cover:
▪ Function declaration
▪ Arrow functions
Functions- Function declaration
▪ Require defining the function name,
optional parameters and a body
▪ Use the keyword function before
the name
▪ Functions always return a value:
▪ explicit return
▪ undefined
Functions- Function declaration
▪ There is no main function in
JavaScript.
▪ Execution begins at the
beginning of the tags or file.
▪ To use functions, you need
to call them and provide
necessary arguments.
▪ You can assign a function to
a variable.
Functions- Function declaration
▪ They were introduced in
EC6
▪ A shorter way of writing a
function
▪ Gets rid of the function
keyword
▪ Introduces the fat arrow =>
▪ Use curly braces when
there are more than one
statements
▪ No return keyword for one
single line statements
Default parameters & templates
▪ Default parameters are
placeholder in the
function declarations:
▪ If an argument is not
passed, it will be
assigned the default
value
▪ ${} is used as a
placeholder in template
literal
Callback functions
▪ It is a function that is
passed as an argument
to another function
▪ The main aim is
making the function to
be executed later
▪ Callbacks are
fundamental in
asynchronous
programming.
Callback functions- setTimeout
▪ An easier way to
demonstrate the
usefulness of callback is
the use of setTimeout
function
▪ It executes of a
function or a code
snippet after a specified
amount of time
▪ setTimeout(callback,
delay);
Object-oriented programming
▪ It is a paradigm that conceptualizes a
program as objects interacting with one
another
▪ The following are three pillars of OOP:
▪ Inheritance
▪ Polymorphism
▪ Encapsulation
▪ JS is a complete OOP language
Object-oriented programming
▪ Real life objects have attributes and
behaviour
▪ In JS attributes & behaviour are
represented as properties and methods
▪ JS supports different type of objects:
▪ Number, String, Boolean (when new is used)
▪ Date
▪ Arrays
▪ Functions
▪ Objects
Creating objects- Literals
▪ You can create an
object in one statement
using object literal
▪ The literal contains
name and value pairs
Creating objects- Literals
▪ You can also create an
object and initialize it
later
▪ Remember const
objects can be modified
but not reassigned
Creating objects- Literals
▪ You can also create an
object using the new
keyword
▪ You can add properties
and methods to the
object.
Creating objects- constructor function
▪ Define the object type
by writing a constructor
function
▪ Create an instance of
the object with the new
operator
▪ The function can allow
you to create more
objects with the same
properties
Creating objects- Classes (ES6)
▪ Classes were added in
ES6.
▪ Defines a blueprint for
creating objects
▪ A constructor- initializes
properties.
▪ The class can have
properties, methods &
static members.
Manipulating objects- properties
▪ Object properties can
be manipulated after the
object has been created
▪ The properties can be
added, modified and
read
▪ There two ways of
accessing properties:
▪ Dot operator
▪ Square brackets
Manipulating objects- methods
▪ For classes, the
methods are added
differently.
▪ There is no need to
define a property for the
method.
The “this” keyword
▪ The “this” keyword in JS
could refer to different
things depending on the
context.
▪ The current object
▪ The global object
▪ In special methods it could
refer to any object ( call,
apply, bind)
Classes- static fields
▪ Static fields and methods
belong to the class.
▪ They can be accessed
using the class name and
not using an instance of the
class.
Call() method
▪ It is used when
you want to
borrow a method
from one object
and apply it to
another object.
▪ The “this” in that
context could
refer to different
objects.
Getters & setters
▪ Getters and setters are
special methods that
can be used to assign
and access object
properties.
▪ They add a layer of
encapsulation
▪ Getters retrieve values
& setters set values.
Inheritance- ES6 Classes
▪ One of the pillars in
OOP
▪ The extend keyword
is used to implement
inheritance in JS
▪ The subclass in
inherits all properties
and methods of the
super or base class
Built in Object methods
▪ There are
several
methods
which you
can use to
manipulate
objects.
JSON- JavaScript Object Notation
▪ The format of JSON is as follows:
{ “key1”:”value”, “key2”:value}
▪ The key always must be in quotes
▪ The values can be of different data
types:
─ String
─ Number
─ Object
─ Boolean
─ Null
JSON- JavaScript Object Notation
▪ You can convert JS
objects to JSON and vise
versa
▪ To convert JS objects to
JSON use JSON.stringify
method
▪ To convert from JSON to
JS object use
JSON.parse()
Iterators
▪ Provides an easy was of
accessing elements in a
collection
▪ They implement an
interface with the following
members:
▪ next() – next value or done
▪ Symbol.iterator – defines
iterator object
Arrays
▪ JS arrays are objects
▪ Unlike arrays in other
languages, JS arrays are
resizable
▪ The elements of an array
can only be accessed using
indices
▪ The are many built in
methods you can use to
manipulate arrays.
Arrays
▪ The
following
are some of
the
common
method of
the Array
class.
Arrays
Arrays
▪ The foreach function
provides a callback
function which execute
the function every time it
loops through the
elements
▪ The filter function returns
elements that satisfy the
condition