0% found this document useful (0 votes)
2 views

WEB DEVELOPMENT JAVASCRIPT

This document provides an introduction to programming, focusing on JavaScript as a high-level, interpreted language used for web development. It covers key concepts such as programming instructions, algorithms, variable declaration, data types, and the program execution cycle. Additionally, it explains how to write a simple JavaScript program, including variable scopes, functions, and the HTML DOM for web page manipulation.

Uploaded by

billy illa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
2 views

WEB DEVELOPMENT JAVASCRIPT

This document provides an introduction to programming, focusing on JavaScript as a high-level, interpreted language used for web development. It covers key concepts such as programming instructions, algorithms, variable declaration, data types, and the program execution cycle. Additionally, it explains how to write a simple JavaScript program, including variable scopes, functions, and the HTML DOM for web page manipulation.

Uploaded by

billy illa
Copyright
© © All Rights Reserved
Available Formats
Download as PPTX, PDF, TXT or read online on Scribd
You are on page 1/ 91

JAVASCRIPT

THE END OF STRUCTURE AND DESIGN AND THE


BEGINNING OF PROGRAMMING
Programming 101

01 02 03 04
WHAT IS KEY WRITING YOUR JAVASCRIPT
PROGRAMMING? PROGRAMMING FIRST JAVASCRIPT VARIABLES
CONCEPTS AND PROGRAM
THE PROGRAM
EXECUTION
CYCLE
What is programming?
 Programming is the process of writing instructions (code) that a
computer can understand and execute to perform specific tasks.
These instructions are written in a programming language such
as Python, JavaScript, C++, or Java.
Key programming concepts
 Various programming languages come with their own pros and
cons but there are concepts that are core and similar to every
programming language. These are discussed in the next slides.
Instructions and code
 In every programming language programmers write step-by-step
commands that tell the computer what to do.
Purpose and Variety
 Different languages exist for different tasks (e.g., Python for data
science, JavaScript for web development). In short, every
programming language was built with the desire to accomplish a
certain purpose in mind. This means that some languages will be
good for certain tasks than others. The programmer has to choose
the best tool for the best job.
 NOTE: here are approximately 700 programming languages in
existence, including both widely used languages and more
esoteric or niche options; however, some lists may only include
notable languages, putting the number closer to 245
Algorithms and Logic
 Every programming language involves writing efficient and logical
sequences of steps to solve a problem. These are referred to as
algorithms.
Compilation and Execution
 Most programming languages need to be translated into a form
that machines can understand before their instructions are carried
out. Based on how the code is translated and executed, a
programming language can either be a compiled language or an
interpreted language. Compiled languages are generally
translated, bundled up and executed once while interpreted
languages are translated and executed line by line. Compiled
languages are generally faster than interpreted languages.
Debugging
 Every programming language has some form of error handling
that helps the programmer fix errors that may deter the program
from execution or that may make execute incorrectly.
The program execution cycle
 From the moment a program is fed to run into a computer to the
moment it returns a result there are various stages it goes
through. This cycle of steps can be called the execution cycle. Its
various steps are outlined in the next slides.
Step 1: Translation.
 This may take two forms. Either compilation or interpretation
based on the type language.
 Computers only understand binary code (0s and 1s), so the
source code must be translated into machine code using either:
 Compilers (e.g., C, C++): Convert the entire program into machine
code before running it.
 Interpreters (e.g., Python, JavaScript): Execute the program line by
line without converting everything at once.
Step 2: Execution.
 Once translated, the program runs, and the computer performs
the instructions step by step.
• Example:
• If a program is designed to add two numbers, it will take
input, process it, and display the result.
• If it's a web app, it might fetch data and display it in a
browser.
Step 3: Handling Input
 Most programs receive data from the user to process and return
as information. After the program has run, it can now be executed
and part of execution may involve an instruction that requires the
user to enter data for processing.
Step 4: Storing data
 A program often takes the input the user has given it and stores it
in a container called a variable where it can reference when it is
performing operations.
Step 5: Data Processing
 In this stage, the program processes the data based on the
algorithm defined by the programmer to return useful information
that the user can make sense of.
Step 6: Output
 If the program has executed successfully without any errors, it will
return the expected value to the user known as an output. If not, it
may give an error message or return an inaccurate value.
Writing your first JavaScript
program
What is JavaScript?
 JavaScript (JS) is a high-level, interpreted programming
language used to make web pages interactive. It is one of the
core technologies of web development, along with HTML and
CSS.
Your first program
 Let’s write some code to see how we can write, run and see the
result of simple hello world program in JavaScript
JavaScript variables and data
types
 In JavaScript, a variable is a container for storing data. It
allows you to store values like numbers, text, or objects and reuse
them later in your program.
Rules for declaring variables
 To declare a variable in Js, we must use the var, let, or const
keyword(a word reserved for a specific purpose in programming
language). Each of these has their use cases as we will see later.
 Variable names must start with a letter, underscore or dollar sign.
 Variable names can’t be a reserved keyword.
 Variable names are case sensitive
 Use camelCase for better readability
 Give names to your variables that relate to the data they are storing
YOUR FIRST PROGRAM!
 You have officially written your first program and become a
programmer but why stop now if you could learn more? I hope to
see you in the oncoming classes as we dive deeper into
programming.
Variables
 In programming, variables are used to hold values. It is necessary
for a program to be able to hold values that it can perform various
operations on.
Variable Declaration
 To declare a variable simply means to create a variable.
 In Js, variables are declared using the var, let and const keywords.
The Var keyword
 This is the traditional way to declare variables. It is function-
scoped and can be re-declared within the same scope.
Example:
var x = 10;
The let keyword
 This is types of variables block-scoped and cannot be re-declared
in the same block. This is preferred over var for better scoping.
Example:
let y = 20;
The const keyword
 Used to declare block-scoped variables that should not be
reassigned. The value itself can be mutable if it's an object or
array.
Example:
const z = 30;
Variable Declaration syntax
let variableName = value;
Breakdown
let: The keyword to declare the variable.
variableName: The name of the variable.
value: The value assigned to the variable.
Example:
let age = 25;
let name = "John";
let isStudent = true;
Variable Declaration Rules
 Must start with a letter, underscore (_), or dollar sign ($).
 Cannot start with a number.
 Can only contain letters, numbers, underscores, and dollar signs.
 Cannot use reserved keywords (e.g., let, const, if).
Example:
let _value = 10; // Valid
let $name = "Jane"; // Valid
let 123name = "Invalid"; // Invalid
Variable Scopes
 Variable scopes are used to define the accessibility of a variable
within JavaScript.
Global variables
 Declared outside any function or block. Accessible throughout the
program.
Example:
var globalVar = "I am global!";
Local Scope
 Declared inside a function or block. Accessible only within that
function or block.
Example:
function greet() {
let localVar = "I am local!";
console.log(localVar);
}
Global
 Applies to let and const. Confined to the block in which they are
declared.
Example:
{
let blockVar = "Block Scoped";
console.log(blockVar);
}
Operators
 In JavaScript, operators are special symbols or keywords used to
perform operations on values (operands) and produce a result.
They are essential for computations, comparisons, logical
decision-making, and manipulating data. They are discussed in
the next slides.
Arithmetic Operators
 These are operators that are used to perform basic mathematical
operations. They take numerical values as their operands and
return a single numerical value.
Assignment Operators
 An assignment operator assigns a value to its left operand based
on the value of its right operand. JavaScript has seven basic
assignment operators as shown in the table below:
Comparison Operators
 A comparison operator compares its operands and returns a
Boolean based on whether the comparison is true or false. It can
be used to compare strings, numbers, Booleans(logical), or object
values. There are eight comparison operators in JavaScript as
shown in the table below:
Logical Operators
 Logical operators are commonly used with Booleans. When they
are used with Boolean values, they return a Boolean value.
JavaScript has three logical operators.
Data Types
 In programming the concept of data-types cuts across all
programming languages. Data types can be defined as the
different types of data that can be stored or used in a program.
JavaScript has seven data types namely: String, Number, Boolean,
Object, Array, Undefined, and Null. They are as discussed below:
JS String
 The string data type is a sequence of characters that are used to
represent text. A string can be written with either single or double
quotes.
Example:
const sentence = “Hello World”;
JS Number
 The number data type is an integer if a floating-point number (a
number with a decimal).
Example:
const x = 4;
JS Boolean
 This is a logical data type that can only have two values: true or
false. Booleans are mainly used for conditional testing (testing
whether a condition is true or false) and they are also the outputs
of comparison operators.
Example:
const isCodingFun = true;
const isMathBoring = false;
JS Object
 The object data type is a collection of related data. Objects contain properties
written in key: value pairs. Each pair is separated by a comma (,). Objects are
written within curly braces. Objects are often used to represent real world objects
within code.

Example:
const apple = {
color: “red”,
size: “big”,
quantity:3,
isSweet:”true”,
}
The Dot operator
 Each value within the object can be accessed using the dot operator.
This is done by writing the name of the object followed by a dot and
then the name of the value to be accessed as shown below:
Example:
apple.color
apple.size
apple.quantity
apple.isSweet
JS Array
 An array in JavaScript is a collection of values each separated with
a comma (,). It is written within square brackets.
Example:
const fruits = [“apple”, “banana”, “mango”]
const marks = [450, 440, 240, 388]
JS Undefined
 If a variable does not have an assigned value or if a programmer
tries to access an undeclared variable, then JavaScript returns an
undefined data type. It is important to understand undefined data
types in JavaScript as they will help in learning to debug programs
and figure out where problems may be. The example below is a
code that would return an undefined data type:
Example:
let title;
JS Null
 The null data type is a special data type denoting a null value –
meaning it’s not an empty string “” or 0. It simply stands for nothing.
Example
const fruit = null
 The null data type is important as it can help us empty a variable.
Example
let fruit = “apple”
fruit = null
The Dynamic Nature of JavaScript
 JavaScript if a dynamically-typed language. What does this mean?
In other languages like C, C++, C#, Java and many others
statically-typed languages, you have to declare a variable by
defining a specific data type that can be stored in that particular
variable. For instance, a variable defined specifically for strings
will only hold strings and cannot hold int and that goes for all the
other types. JavaScript on the other hand decides the type of
variable during compilation by checking for the type of data
stored within it. This makes it easy to write code in but slower
than the statically-typed language.
JS Functions
 Functions are one of the fundamental building blocks of JavaScript.
A function is a set of statements that performs a task or produces
a value. It is executed when it called or invoked by something. A
function in JavaScript can be in some instances also referred to as
methods.
Function Definition
 For functions to be called and used in JavaScript, they need to be
defined. Functions in JS can be defined in one of two ways. These
is described in the next slides.
Using the function Keyword
 In this method, a function is defined using the function keyword followed by:
 The name of the function
 A list of parameters enclosed in parentheses
 The block of codes or the statements enclosed in curly brackets.
Example:
function sayHello (name){
console.log(`hello ${name}`)
}
 The function above takes the name of an individual as a parameter and returns a greeting.
Below is another example of a function that takes two numbers and returns their sum.
Using the JS arrow function

 This method of defining functions is considered more compact than


the regular function expression that has been discussed above.
 This method defines functions by declaring their names using the
const keyword followed by:
 An equal sign, a parenthesis for the variables, an arrow, the code
block within curly braces. Here is an example demonstrating this:
Example
const add = (a,b) => {
console.log(a+b)
}
‘Parameterless’ Arrow functions
 In a case where the function takes only a single parameter, there
is no need to enclose it within parenthesis as shown below:
Example
const sayHello = name => {
console.log(`hello ${name}`)
}
Functions are black boxes…
 From the examples above, we can liken a function to a black box
that takes in raw products and returns complete merchandise
depending on the specifications of the programmer. These are just
simple examples, in real life, functions can span multiple lines of
code depending on what the programmer intends to achieve.
JS Loops
 In programming, there are times when we need to run the same
statement over and over until we get a desired result or until a
given condition is met. To achieve this, programmers make use of
loops. This section discusses the various ways of implementing
loops in JavaScript.
HTML DOM
 The HTML DOM (Document Object Model) is a programming
interface that allows JavaScript (or other programming languages)
to interact with and manipulate HTML documents. It represents
the structure of an HTML page as a tree-like hierarchy of objects,
where each element (like <div>, <p>, <h1>, etc.) is treated as a
node.
HTML DOM
How does the DOM work?
 The DOM treats the entire web page as a structured tree of
objects. JavaScript can read, modify, add, or delete elements in
the DOM dynamically. Each element in the HTML document is an
object that can be accessed and manipulated using JavaScript.
DOM selectors
 DOM selectors allow JavaScript to access and manipulate
elements in an HTML document. There are different types of
selectors, each suited for different use cases.
Selecting by ID
 Selects a single element with a specific ID.
 Returns one element (since IDs are unique).
 Fastest method for selection.
Selecting by class
 Selects all elements with a given class name.
 Returns a live HTMLCollection (similar to an array).
Selecting by tag name
 Selects all elements with a specific tag name (div, p, h1, etc.).
 Returns an HTMLCollection.
Selecting using a queryselector
 Selects the first matching element based on CSS-style selectors.
 Can select IDs (#id), classes (.class), and tags (tag).
Selecting using querySelectorAll
 Selects all elements matching a CSS selector.
 Returns a NodeList, which can be looped through.
JS Events
 JavaScript events are actions or occurrences that happen in the
browser, usually as a result of user interactions or browser
actions. JavaScript allows us to "listen" for these events and
execute code when they happen.
Mouse Events
 Triggered by user interactions with
the mouse.
Keyboard events
 Triggered when a user interacts with
the keyboard.
Form Events
 Triggered when a user interacts with a
form element.
Window Events
 Triggered when something happens to the
browser window.
Handling Events
 There are three main ways to add event listeners in JavaScript
as discussed in the following slides.
Inline Event handlers
These add an event listener to a JS element using the event attribute.
Using JS event property
 This involves adding an event to an element using an
event property
Using JS addEventListener method
 This involves adding an event listener to an element using the
addEventListener method which takes in the type of event to be
detected and the function to be invoked as methods
CONSUMING APIs WITH JS
JS Fetch API

WHAT ARE HOW DO THEY JAVASCRIPT


WORK? FETCH API
APIS?
What are APIs in programming?
 An API (Application Programming Interface) is a set of rules
and protocols that allows different software applications to
communicate with each other. It defines how requests and
responses should be formatted, enabling seamless interaction
between systems without exposing their internal implementation
details.
Simply put…
 An API (Application Programming Interface) is like a menu in
a restaurant.
 Imagine you go to a restaurant:
• You (the customer) don’t go into the kitchen to cook the food.
• Instead, you look at the menu (API) and order what you want.
• The waiter (API call) takes your order to the kitchen (server) and
brings back the food (data).
Think of an API like a restaurant
Types of APIs
 Web APIs – Used to get data over the internet (e.g., weather,
maps, movies).
 Library APIs – Functions built into programming languages (e.g.,
Math API in JavaScript).
 Operating System APIs – Used by software to interact with
hardware (e.g., Windows API).
Features of APIs
1. Abstraction: Hides the complexity of a system and provides a
simplified way to interact with it.
2. Interoperability: Allows different software components to
communicate, even if they are built using different technologies.
3. Standardization: Follows predefined rules (e.g., REST, GraphQL,
SOAP) for consistent interactions.
4. Security: Often requires authentication (e.g., API keys, OAuth,
JWT) to control access.
How do APIs works?
 The client (frontend) makes requests, and the server (backend)
processes them and sends responses.
 Stateless – Each request is independent; the server doesn’t
remember past interactions.
 Resource-Based – Data is treated as "resources" (e.g., users,
products), each identified by a URL.
 Use of Standard HTTP Methods – CRUD operations are mapped
to HTTP methods: (GET: retrieve data from a db, POST: create new
data, PUT: update existing data, DELETE: remove data)
Requests and Responses
Responses can either be a resource
or an error….
JSON(JavaScript Object
Notation)
 This is not someone’s name it is a lightweight data format used
to store and exchange data between a server and a client. It is
easy to read, write, and parse, making it a popular choice for
APIs and web applications.
JS Fetch API
What is JS fetch API?
 The Fetch API is a built-in JavaScript feature that allows you to
make HTTP requests to servers, such as fetching data from an API
or sending data to a server. It is modern, easy to use, and
returns a Promise.
How does it work?
 You call fetch(url) – This sends a request to the given URL.
 It returns a Promise – The Promise resolves with a Response
object.
 You process the response – You typically convert it to JSON
using .json().
 You handle the data or errors – You can use .then() for success and
.catch() for errors.
What is a promise in the fetch
API?
 When you use fetch(), JavaScript sends a request to a server and
waits for a response.The server takes time to respond, so
JavaScript doesn’t stop everything—it just creates a Promise.
 You tell JavaScript what to do when the response arrives
using .then() (for success) and .catch() (for errors).
Basic syntax of the fetch API
What’s happening here?

 fetch("URL") sends a request.


 .then(response => response.json()) converts the response into
JSON format.
 .then(data => console.log(data)) logs the retrieved data.
 .catch(error => console.error(error)) handles any errors.
Now let’s build something cool

You might also like