Introduction to JavaScript
and TypeScript
JavaScript
2
JavaScript at the Frontend of a web app:
Primary components of a dynamic web page
• HTML (Hyper Text Markup Language)
• HTML is the markup language that we use to structure and give meaning to web content
• For example, HTML provides tags to define paragraphs, headings, and data tables, or embedding
images and videos in a web page.
• CSS (Cascading style sheet)
• CSS is a language of style rules that we use to apply styling to our HTML content
• For example, using CSS we can set background colors and fonts, and lay out content in multiple
columns, among other things.
• JavaScript
• JavaScript is the Programming Language for the Web.
• JavaScript can update and change both HTML and CSS inside a web page.
• For example, JavaScript enables us to create dynamically updating content, control
multimedia, animate images, etc.
• A web browser provides runtime environment for JavaScript
3
Primary components of a dynamic web page
<input onclick="update()" HTML
type="button"
JavaScript
value="Open"
CSS
id="button1">
</input>
<style>
input {
font-family: helvetica, sans-serif; <script>
letter-spacing: 1px; function update() {
border: 4px solid rgb(200 200 0 / 60%); var b1 = document.getElementById("button1")
background-color: rgb(0 217 255 / 60%); if (b1.value == "Open")
color: rgb(200 200 0 / 100%); b1.value = "Close"
box-shadow: 1px 1px 2px rgb(0 0 200 / 40%);
else
padding: 3px 10px;
cursor: pointer;
b1.value = "Open"
} }
</script>
</style>
4
JavaScript at the Backend
• Node.js is a runtime environment that allows developers to run
JavaScript outside the browser.
• It is built on the V8 JavaScript engine (the same engine that powers
Google Chrome)
• It enables server-side development using JavaScript, often used to
create APIs that interact with databases and front-end applications.
5
JavaScript
• Developers often refer to using JavaScript without
any significant language extensions or frameworks
as “Vanilla JavaScript”: referring to it being the
familiar, original flavor.
• JavaScript is a multi-paradigm language. It
supports object-oriented, functional and
procedural programming.
6
JavaScript: Type of a variable may change
let x = 100;
console.log("Type of x =", x, ": ", typeof x); number
x = "Hello World";
string The type of
console.log("Type of x =", x, ": ", typeof x);
variable ‘x’
changes as values
of different types
x = false;
are assigned to it
console.log("Type of x =", x, ": ", typeof x); boolean
x = ["Green", "Red", "Orange"];
console.log("Type of x =", x, ": ", typeof x); object
7
JavaScript: Type of a variable may change
x = function helloWorld() {
return "Hello World!"; function
}; The type of
console.log("Type of x =", x, ": ", typeof x);
variable ‘x’
changes as values
of different types
are assigned to it
x = { Name: "Ahmad", Address: "Lahore" }; object
console.log("Type of x =", x, ": ", typeof x);
8
TypeScript
9
What is TypeScript?
• A programming language that includes all the existing JavaScript
syntax, plus additional TypeScript specific syntax for defining and
using types.
10
Type Checking
• A type checker is a program that analyzes code to ensure that values
and variables conform to expected types before execution. It helps
catch errors early, improving code reliability.
• Static Type Checking
• Check types at compile-time (before running the code).
• Some statically typed languages:
• TypeScript, Rust,
• Dynamic Type Checking
• Check types while the program is running.
• Some dynamically typed languages:
• JavaScript
• Python
11
TypeScript Compiler
• TypeScript compiler runs the type checker, reports any issues,
then outputs the equivalent JavaScript code.
• Remember that Web browsers can execute JavaScript code only
12
TypeScript: Declaring a variable
• The keywords let and var can both be used to declare a new
variable in TypeScript.
• The difference between let and var is in the scope of the variables
they create:
• Variables declared using the keyword let are only available inside the
block where they’re defined.
• Variables declared using the keyword var are available throughout the
function in which they’re declared.
13
TypeScript: Declaring a variable and Type inference
let n = 100;
console.log("Type of n =", n, ": ", typeof n); Type of n: number
var m = 500;
Type of m: number
console.log("Type of m =", m, ": ", typeof m);
var address; Type of address: undefined
console.log("Type of address =", address, ": ", typeof address);
address = "Lahore"; Type of address: string
console.log("Type of address =", address, ": ", typeof address);
14
TypeScript: Declaring a variable
• Variables that can’t have their initial type inferred go through
what’s called an evolving type ‘any’
• TypeScript will evolve its understanding of the variable’s type each
time a new value is assigned to it.
• Allowing variables to be evolving any typed—and using the any
type in general—defeats the purpose of TypeScript’s type
checking.
• TypeScript works best when it knows what type your values are
meant to be.
15
Different ways of defining a function
function hello1() {
console.log("Hello World-1"); A simple function that prints
} a message in the console
hello1();
var hello2 = function hello2(msg: string) {
console.log(msg); Functions can be assigned
}; to variables
hello2("Hello World-2")
const hello3 = function (msg: string) {
console.log("Hello " + msg); Typically, a function should
}; be assigned to a const
hello3("Hello World-3");
16
Different ways of defining a function
var add1 = function (n: number, m: number) {
Return type is inferred by
return n + m; TypeScript compiler
};
console.log(add1(5, 7));
var add2 = function (n: number, m: number): number {
return n + m; Return type is explicitly
}; declared
console.log(add2(5, 7));
var addFun;
Calling functions addFun
addFun = add1;
and add1 is same
console.log(addFun(6, 10)); 17
Function Parameters
function f1(x: number, y?: number) {
if (y) y is an optional parameter
return x * y;
return x * x;
}
console.log("f1: ", f1(5));
console.log("f1: ", f1(5, 7));
function f2(x: number, y: number = 5) { y has default value of 5
if (y)
return x * y;
return x * x;
}
console.log("f2: ", f2(5));
console.log("f2: ", f2(5, 7));
18
Function Parameters
function f3(name: string, ...frequencies: number[])
{
console.log("f3: name: ", name) Some functions are made to be called
for (const frequency of frequencies) {
with any number of arguments. The ...
console.log(frequency);
spread operator may be placed on the
}
last parameter in a function definition to
return ("f3 called") indicate any “rest” arguments should all
} be stored in an array.
console.log("f3: ", f3("Name-1"));
console.log("f3: ", f3("Name-2", 4, 5, 6));
19
Passing functions as parameters
function f(g: (n: number, m: number) => number) {
console.log("Function f: " + g(4, 9));
return "abcd";
}
The function f takes a function as a
parameter. The type of the parameter is
const add = function (n: number, m: number): number { (n: number, m: number) => number
return n + m;
};
console.log(f(add));
20
Passing functions as parameters: map
const sqr = function (n: number) { return n * n; };
var nums = [1, 5, 8, 9];
const map = function (g: (n: number) => number, data: number[]) {
var output: number[] = [];
for (var i = 0; i < data.length; i++)
output.push(g(data[i]));
return output;
};
var arr = [4, 5, 10];
var result = map(function (n: number) { return n * 2; }, arr);
console.log(result)
21
Lambda Functions
const product = (x: number, y: number) => x * y;
const addition = (x: number, y: number) => {
var sum = x + y;
return sum;
22
Nested Functions
function outer(x: number, y: number) {
let temp = x * y;
function inner(n: number, m: number) {
let temp = n + m;
return x * temp + y;
}
let v = inner(2, 3);
console.log("Inner returned: " + v);
return v * 3;
}
console.log("Outer returned: " + outer(4, 3));
23
Nested Functions
function outer(x: number, y: number) {
let temp = x * y;
function inner(n: number, m: number) {
let temp = n + m;
return x * temp + y;
}
return inner;
}
console.log("Outer returned: " + outer(4, 3));
The tempFun here is the inner function, that remembers scope of the
let tempFun = outer(4, 3); outer function, i.e., it remembers its context
console.log("tempFun: " + tempFun(2, 3)); 24
Generic Functions
function genericA<T>(x: T): void {
console.log("x = " + x + ", is of type: " + typeof x); The function genericA takes a parameter of
} type T which can be any type as far as the
body of the function can work on that type.
genericA(4);
genericA("ABC");
25
Generic Functions
function genericB<T1, T2>(x: T1, y: T2): T1 {
console.log("x = " + x + ", is of type: " + typeof x);
console.log("y = " + y + ", is of type: " + typeof y); The function genericB takes two parameters
of type T1 and T2, which can be any types as
return x; far as the body of the function can work on
} those types. The function returns a value of
type T1
genericB(1, true);
genericB<number, boolean>(0, false);
genericB<number, number>(0, 100);
26
Union Types
let u1: string | number = "abc";
console.log("Type of u1 =", u1, ": ", typeof u1);
u1 = "Test"; u1 can either be a number or a string
let l = u1.length;
u1 = 55;
console.log("Type of u1 =", u1, ": ", typeof u1);
let u2: string | number = 45
u2 = u2 * 2;
console.log("Type of u2 =", u2, ": ", typeof u2);
27
Arrays
Let nums: number[];
nums = [4, 8, 15, 16, 23, 42];
let arrNumsOrStrings: (string | number)[];
arrNumsOrStrings = ["AB", 4, 6, "DE"] Using the concept of union types, arrays may
contain elements of different types
for (let i = 0; i < arrNumsOrStrings.length; i++)
console.log(arrNumsOrStrings[i])
28
Arrays: Spreads
const employees = ["Ahmad", "Ali"];
const employeeIds = [100, 300];
Arrays can be joined together using the spread
const joined = [...employees, ...employeeIds] operator (... )
for (let i = 0; i < joined.length; i++)
console.log(joined[i])
29
Tuples
let idName: [number, string];
idName = [4, "A"]
idName = [5, "B"]
console.log("idName: ", idName);
30
Looping
var result = [4, 5, 10];
for (let i = 0; i < result.length; i++)
console.log(result[i]);
var result = [4, 5, 10];
for (let num of result) Iterate over each element of the array
console.log(num);
var numbers = [1, 5, 8, 9]; forEach() method calls a function for
each element in the array. forEach() is
numbers.forEach(function (val, i) { console.log(val + " " + i); }); a function (not a loop) but it works like
a loop.
31
Common Commands
• Required Software
• Install the LTS release of NodeJS from: https://nodejs.org/en/download/
• Install typescript on your machine
• npm install -g typescript
• Using Typescript compiler
• tsc <filename.ts> (tsc is Typescript compiler)
• tsc --version
• tsc –help
• Execute a JavaScript file on command line using node.
• node <filename>
• Execute a TypeScript file on command line using node.
• ts-node <filename>
32
References
• Learning TypeScript by Josh Goldberg
• Node.js in Action by Alex Young etc.
33