Introduction To Javascript
Introduction To Javascript
JavaScript
Recap
What is JavaScript
• HTML is static, JavaScript add a level of interactivity to
an otherwise static web site.
2. Chrome DevTools
• Provides advanced debugging with the Sources panel.
• Step through code, set breakpoints, and inspect execution.
• Similar tools are available in other browsers for easy adaptation.
JavaScript Variables
• Using var
For global/function scoped variables that can be
changed and redeclared.
• Using let
For block scoped variables where we want to be
able to change the value.
Modern JS uses let for all mutable variables
• Using const
For constant block scoped values that cannot be
changed later on.
• Variables can also be automatically assigned
Variable Scope
Scope determines the accessibility (visibility) of variables.
JavaScript has 3 types of scope:
1. Block scope
2. Function scope
• Local scope
3. Global scope
• Loops: How do you do almost the same thing over and over again in a controlled
manner?
Conditionals
• if: an if statement executes a code block if the specified condition is truthy
• Else if: An if statement can be followed by zero or more else-if statement where each statement can have their
own condition and associated code block
Conditionals
• else: the code block for else is executed if and only if none of the other conditions are truthy.
• Ternary: the ternary operator often a fast way of writing an if statement combined with an else statement that
works as an expression, meaning we can bind the result. It requires three conditions: a condition, an expression if
the condition is truthy and a condition if the expression is false
Conditionals
• Switch: Switch statements are great for situations where you want to conditionally handle a fixed set of values.
• A switch statement evaluates an expression, and matches its value with a list of case values, selects the first
case that matches and executes the statements in that case as well as the cases that follow
The Shift from Static to Dynamic Data
Problem with Static Data:
The Solution:
• XMLHttpRequest enabled web apps to send/receive data asynchronously without reloading the
page, paving the way for modern dynamic web apps.
Introduction to REST Architecture
REST- Representational State Transfer
REST is an architectural style for distributed hypermedia systems that most modern web services adhere to.
Roy Thomas Fielding presented an architectural style for distributed hypermedia systems in his dissertation in
the year 2000 that he called the REST architecture. The REST architecture has over time become the
defacto standard of web service APIs, and it is highly probable that whatever API we need to use provides
a RESTful interface.
RESTful Guiding Principles
• Client-server: Client concerns (e.g., the website) should be separate from server concerns to avoid tying server logic to
a specific client type. This simplifies server logic and supports multiple platforms.
• Stateless: Each client request should be independent, allowing the server to handle each request without relying on
previous interactions. This simplifies server logic but may add complexity to the client.
• Cacheable: Servers can label responses as cacheable, enabling clients to reuse responses for similar future requests,
which improves efficiency.
• Uniform interface: The server must offer a consistent interface for all components, following four constraints: resource
identification, manipulation through representations, self-descriptive messages, and hypermedia as the engine of the
application. state.
• Layered system: Server components should only interact with their immediate layers, limiting system complexity and
promoting components' independence.
• Code on demand (optional): Servers can provide code for clients to execute as needed, reducing the initial payload and
allowing clients to load only the necessary code later.
HTTP Methods in REST APIs
• GET: Used to fetch resources
• POST: Used to create resources
• PUT: Used to modify resources
• PATCH: Used to modify parts of resources
• DELETE: Used to delete resources
Asynchronous JavaScript
Problem:
● We said the Web is asynchronous
● But JavaScript is famously single-threaded, meaning
that it can only execute one code chunk at the same
time.
Solution:
● Asynchronous programming. This allows tasks to
run without blocking the main thread, improving
responsiveness.
Synchronous Code
● JS executes one task at a time, which can lead to blocking.
Asynchronous
Code
States of a Promise:
• Pending: Initial state, waiting for operation.
• Fulfilled: Operation succeeded, resolved with a value.
• Rejected: Operation failed, rejected with an error.
Promises
Example
<button id="promise-btn">Fetch with Promise</button>
<p id="promise-result">Promise result will appear
here</p>
document.getElementById('promise-
btn').addEventListener('click', () => {
fetchWithPromise('https://jsonplaceholder.typicode.
<script>
com/todos/1') //Free fake and reliable API for testing
function fetchWithPromise(url) {
and prototyping.
return new Promise((resolve, reject) => {
.then(data => {
const xhr = new XMLHttpRequest();
document.getElementById('promise-
xhr.open('GET', url);
result').textContent = data;
xhr.onload = () => {
})
if (xhr.status === 200) {
.catch(err => {
resolve(xhr.responseText); // success
document.getElementById('promise-
} else {
result').textContent = err;
reject('Error: ' + xhr.status); // failure
});
}
});
};
xhr.send();
</script>
});
}
Async/Await
The promise syntax is verbose and a long chain of promises can be hard to read
The return value of functions tagged with async is automatically converted to promises.
Await
The await keyword waits for a Promise to settle. This keyword is only permitted inside async functions and
blocks execution of the code that follows until the specified Promise has settled
Document Object Model
JavaScript has excellent support for manipulating web documents via the Document Object Model
(DOM)
For security reasons, JavaScript is not allowed to control or manipulate the web browser however it
wishes; it uses Web API standards.
For security reasons, JavaScript is not allowed to control or manipulate the web browser however it
wishes; it uses Web API standards.
Other methods:
•By Tag: document.getElementsByTagName("p")
•By Class: document.getElementsByClassName("box")
•By ID: document.getElementById("logo")
Modifying DOM
Elements
Most attributes that can be set directly
on HTML elements can also be
accessed and modified using JavaScript.
This includes css.
Creating New DOM Elements
Use createElement to add elements dynamically
Inserting DOM Elements
`append` `prepend`
Reacting to events
Event Listeners: React to user interactions (e.g., clicks).
https://www.w3schools.com/js/
https://developer.mozilla.org/en-US/docs/Web/JavaScript
https://devdocs.io/javascript/
https://javascript.info/