[go: up one dir, main page]

0% found this document useful (0 votes)
11 views40 pages

Introduction To Javascript

Uploaded by

eddiemens0462
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
11 views40 pages

Introduction To Javascript

Uploaded by

eddiemens0462
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 40

Introduction to

JavaScript
Recap
What is JavaScript
• HTML is static, JavaScript add a level of interactivity to
an otherwise static web site.

• JavaScript is a scripting language

• Scripting languages are lightweight programming


languages

• Scripting languages allow programs to be designed and


run to automate tasks in different environments

• A JavaScript consist of lines of executable computer


code

• JavaScript is a programming language like C or python,


but usually runs directly in our browsers.
History of JS
● JavaScript was created by Brendan Eich while he was working at
Netscape the company behind the Navigator web browser.

● Initially named LiveScript, it was quickly renamed JavaScript to


capitalize on the popularity of the Java programming language

● Microsoft copied JavaScript and implemented it in Internet Explorer,


renaming it Jscript
● In 2008, Google launched its V8 JavaScript engine, significantly
improving JavaScript's performance.
● This, along with the success of Firefox and Chrome, helped reclaim
market share from Internet Explorer.
● Today, JavaScript is a mature language, with standardized features
that work consistently across all major web browsers.
How do we use JS
● There are two ways to add JS to your HTML pages:
1. Script tag 2. Separate JS file (.js)
<script>
// we can write our JavaScript here
/* don't worry you are not supposed to
understand any of this yet */
const h2 = document.querySelector("#largeAndBold")
h2.addEventListener("click", (e) => {
console.log("I was clicked")
})
</script>
<h2 id="largeBold">
I am large and bold.
</h2>
Developer Tools
Modern web browsers have tool to help developers identify exact errors.
Two effective methods for debugging JS:
1. Console Logging
• Use console.log() to track variables and execution flow.
• Quick and simple for small issues.

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

Variables are Containers for Storing Data


JavaScript Variables can be declared in 3 ways:

• 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

One of the differences between var and let is :


- var will have function scope whereas let will have block scope.

Function scope is within the function.


Block scope is within curly brackets.
Global Scope: Variables declared Globally (outside any function)
have Global Scope. Global variables can be accessed from
anywhere in a JavaScript program.
Functions
Functions are a named list of statements and
declarations with pre-defined input parameters
and output values.

Functions are regular values that can be


assigned to constants or variables.

Reusability: allow us to reuse logic without


repeating code
Function Syntax
Functions can be defined using two slightly different
syntaxes:
1. Regular notation
2. Arrow function

Arrow Function Notation:


arrow function notation allow us write shorter more
concise functions
The arrow function is defined by binding a function to a
let, const or var declaration.
Data Types
Control Flow
• Control flow refers to the order in which programs are executed.

• Conditionals: How do we make decisions in our code?

• 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:

• Reloading the page for every interaction.


• Inefficient for real-time applications like collaborative editors or messaging platforms.
The Evolution:
• Before 1998: Full-page reloads were required for data updates.
• 1998: Introduction of XMLHttpRequest by Microsoft.
• 2006: W3C standardizes XMLHttpRequest across browsers.

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

Allows non-blocking execution.


Event Loop: Handles asynchronous operations in the
background, allowing the main thread to continue.
Example: Using setTimeout() to introduce
asynchronous behaviour
Callbacks
• callbacks are functions passed
to another function that starts
executing code in the
background
Promises
Callback are good but nesting multiple callbacks creates difficult-to-read and maintain
code.

Promises allow us to represent an operation that is expected to complete sometime in


the future and promises to give us either a value on completion or an error on failure.

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

async and await make promises easier to write


async makes a function return a Promise
await makes a function wait for a Promise
Async
The async keyword is used to tag a function as a function returning a Promise.

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.

The main parts of the browser you can manipulate:


• Navigator: Represents the state and identity of the browser and can be accessed through the
Navigator object.
• Window: Represents the browser tab that a web page is loaded into and can be accessed
through the Window object.
• Document: Represent the actual page that is loaded into the window and can be accessed
through the Document object.
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.

The main parts of the browser you can manipulate:


• Navigator: Represents the state and identity of the browser and can be accessed through the
Navigator object.
• Window: Represents the browser tab that a web page is loaded into and can be accessed
through the Window object.
• Document: Represent the actual page that is loaded into the window and can be accessed
through the Document object.
Selecting Elements in the DOM
Use querySelector for modern selection:

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).

The addEventListener method takes two mandatory


parameters:
• the type of the event we want to listen for
• function that should be called when an even of that
type happens.
ADDITIONAL RESOURCES

https://www.w3schools.com/js/
https://developer.mozilla.org/en-US/docs/Web/JavaScript
https://devdocs.io/javascript/
https://javascript.info/

You might also like