Unit 4 PDF
Unit 4 PDF
JavaScript functions are executed in the sequence they are called. Not in the sequence they are defined.
This example will end up displaying "Goodbye":
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Function Sequence</h2>
<p>JavaScript functions are executed in the sequence they are called.</p>
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myFirst() {
myDisplayer("Hello");
}
function mySecond() {
myDisplayer("Goodbye");
}
myFirst();
mySecond();
</script>
</body>
</html>
1
mySecond();
myFirst();
</script>
</body>
</html>
2
<p id="demo"></p>
<script>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
function myCalculator(num1, num2) {
sum = num1 + num2;
myDisplayer(sum);
}
myCalculator(5, 5);
</script>
</body>
</html>
The problem with the first example above, is that you have to call two functions to display the result.
The problem with the second example, is that you cannot prevent the calculator function from displaying the result.
Now it is time to bring in a callback.
JavaScript Callbacks
A callback is a function passed as an argument to another function.
Using a callback, you could call the calculator function (myCalculator) with a callback and let the calculator function run
the callback after the calculation is finished:
Example:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Callbacks</h2>
<p>Do a calculation and then display the result.</p>
<p id="demo"></p>
<script>
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
function myCalculator(num1, num2, myCallback) {
sum = num1 + num2;
myCallback(sum);
}
myCalculator(5, 5, myDisplayer);
</script>
</body>
</html>
3
In the example above, myDisplayer is the name of a function.
It is passed to myCalculator() as an argument.
Asynchronous Javascript:
In the real world, callbacks are most often used with asynchronous functions.
A typical example is JavaScript setTimeout().
Where callbacks really shine are in asynchronous functions, where one function has to wait for another function (like
waiting for a file to load).
In the example above, myFunction is used as a callback.
myFunction is passed to setTimeout() as an argument.
3000 is the number of milliseconds before time-out, so myFunction() will be called after 3 seconds.
In this example, function(){ myFunction(“BMS College!!!"); } is used as a callback. It is a complete function.
The complete function is passed to setTimeout() as an argument.
Instead of passing the name of a function as an argument to another function, you can always pass a whole function
instead:
<!DOCTYPE html>
<html>
<body>
4
<h2>JavaScript SetTimeout()</h2>
<p>Wait 3 seconds (3000 milliseconds) for this page to change.</p>
<h1 id="demo"></h1>
<script>
setTimeout(function() { myFunction(“BMS College !!!"); }, 3000);
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
}
</script>
</body>
</html>
<!DOCTYPE html>
<html>
<body style="text-align: center">
<h1>JavaScript Functions</h1>
<h2>Callback Functions</h2>
<p id="demo"></p>
<script>
// Create an Array
const myNumbers = [4, 1, -20, -7, 5, 9, -6];
// Call removeNeg with a Callback
const posNumbers = removeNeg(myNumbers, (x) => x >= 0);
// Display Result
document.getElementById("demo").innerHTML = posNumbers;
// Remove negative numbers
function removeNeg(numbers, callback) {
const myArray = [];
for (const x of numbers) {
if (callback(x)) {
myArray.push(x);
}
}
return myArray;
}
</script>
</body>
</html>
JavaScript is an asynchronous language, which means that it can handle multiple tasks
simultaneously. Callbacks are a fundamental aspect of JavaScript, as they allow you to run code after
an asynchronous operation has been completed.
A callback is a function that is passed as an argument to another function, and is called after the main
function has finished its execution. The main function is called with a callback function as its argument,
and when the main function is finished, it calls the callback function to provide a result. Callbacks allow
you to handle the results of an asynchronous operation in a non-blocking manner, which means that
the program can continue to run while the operation is being executed.
6
Asynchronous operations are operations that take a significant amount of time to complete, such as
network requests, file I/O, and database queries. If these operations were executed synchronously, the
program would freeze and wait for the operation to complete before continuing. This can lead to a
poor user experience, as the program would appear unresponsive.
Callbacks allow you to continue executing code while the operation is being executed in the
background. Once the operation has completed, the callback function is called with the result of the
operation. This way, you can ensure that the program remains responsive and the user experience is
not impacted.
Real-Life Examples:
o Loading images on a website: When you load a website, images can take a while to load,
especially if they’re large. If images were loaded synchronously, the website would freeze and
wait for each image to load before continuing. With callbacks, you can load the images
asynchronously, which means that the website continues to load while the images are being
loaded in the background.
o Handling form submissions: When a user submits a form, it takes time to process the data and
send it to the server. If the form submission was executed synchronously, the user would have
to wait for the data to be processed and sent before the form can be submitted. With callbacks,
you can handle the form submission asynchronously, which means that the user can continue
to interact with the form while the data is being processed and sent in the background
Eg1:
function mainFunction(callback) {
console.log("Performing operation...");
// Use setTimeout to simulate an asynchronous operation
setTimeout(function() {callback("Operation complete");}, 1000);}
7
Eg2:
// Define an array of numbers
var numbers = [1, 2, 3, 4, 5];
Eg3:
// program that shows the delay in execution
function greet() {
console.log('Hello world');
}
function sayName(name) {
console.log('Hello' + ' ' + name);
}
// calling the function
setTimeout(greet, 2000);
sayName('John');
8
The setTimeout() method executes a block of code after the specified time.
Here, the greet() function is called after 2000 milliseconds (2 seconds). During this wait, the sayName('John'); is
executed. That is why Hello John is printed before Hello world. The above code is executed asynchronously (the second
function; sayName() does not wait for the first function; greet() to complete).
Arrow function
Arrow function {()=>} is concise way of writing JavaScript functions in shorter way. They make our code more structured
and readable.
Example:
O/p:
9
Arrow functions allow us to write shorter function syntax:
<!DOCTYPE html>
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows the syntax of an Arrow Function, and how to use it.</p>
<p id="demo"></p>
<script>
myFunction = (a, b) => a * b;
document.getElementById("demo").innerHTML = myFunction(4, 5);
</script>
</body>
</html>
10
It gets shorter! If the function has only one statement and the statement returns a value, you can remove the
brackets and the return keyword.
In fact, if you have only one parameter, you can skip the parentheses as well:
Arrow Function Without Parentheses:
<!DOCTYPE html>
11
<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows that if you have only one parameter in an Arrow Function, you can skip the parentheses.</p>
<p id="demo"></p>
<script>
var hello;
hello = val => "Hello " + val;
document.getElementById("demo").innerHTML = hello("Universe!");
</script>
</body>
</html>
OR
o/p:
OR
12
13
o/p:
o/p:
o/p:
o/p:
Arrow Function without Parameters
const gfg = () => {
console.log( "Hello World!" );
}
gfg();
14
Arrow Function with Parameters
const gfg = ( x, y, z ) => {
console.log( x + y + z )
}
gfg( 10, 20, 30 );
Example:
15
Arrow functions cannot be used as constructors.
These functions are anonymous and it is hard to debug the code.
Arrow functions cannot be used as generator functions that use the yield keyword to return multiple
values over time.
JSON
The JSON syntax is derived from JavaScript object notation syntax, but the JSON format is text only. Code for
reading and generating JSON data can be written in any programming language.
JSON Example
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}
The JSON Format Evaluates to JavaScript Objects:
The JSON format is syntactically identical to the code for creating JavaScript objects.
Because of this similarity, a JavaScript program can easily convert JSON data into native JavaScript objects.
16
Note: JSON names require double quotes. JavaScript names do not.
JSON Values
In JSON, values must be one of the following data types:
a string
a number
an object
an array
a boolean
null
In JavaScript values can be all of the above, plus any other valid JavaScript expression, including:
a function
a date
undefined
JSON Arrays:
JavaScript Array and JSON Array are nearly the same. String, array, boolean, integer, object, null, and boolean values can
all be stored in JSON arrays. Values are separated by commas in the JSON array. The [] operator can be used to access
array elements.
Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
const obj = JSON.parse(text);
Example:
<!DOCTYPE html>
<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>
<script>
text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';
const obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj.employees[1].firstName + " " + obj.employees[1].lastName;
</script>
</body>
</html>
18
Example:
// JSON object
const data = {
"name": "John",
"age": 22,
"hobby": {
"reading" : true,
"gaming" : false,
"sport" : "football"
},
"class" : ["JavaScript", "HTML", "CSS"]
}
// accessing JSON object
console.log(data.name); // John
console.log(data.hobby); // { gaming: false, reading: true, sport: "football"}
console.log(data.hobby.sport); // football
console.log(data.class[1]); // HTML
20
Example: Convert a JSON Text to a JavaScript Object
HTTP headers
HTTP headers contain metadata in key-value pairs that are sent along with HTTP requests and responses. They can be
used to define caching behavior, facilitate authentication, and manage session state. HTTP headers help the API client
and server communicate more effectively—and enable developers to optimize and customize the API’s behavior.
Accept
The Accept header defines the media types that the client is able to accept from the server.
User-Agent
The User-Agent header identifies the web browser or client application that is making the request, which
enables the server to tailor its response to the client.
Authorization
The Authorization header is used to send the client’s credentials to the server when the client is attempting to
access a protected resource.
Content-Type
The Content-Type header identifies the media type of the content in the request body.
Cookie
The client can use the Cookie header to send previously stored cookies back to the server.
Content-Type
The Content-Type response header is the counterpart of the Content-Type request header, as it indicates the
type of data that the server is sending to the client. The header value typically includes the media type (such as
text/html, application/json, image/jpeg, and audio/mp3), as well as any optional parameters.
Cache-Control
The Cache-Control header controls caching behavior in the client’s browser or intermediate caches. It defines
how the response can be cached, when it expires, and how it should be revalidated.
Server
The Server header includes the name and version of the server software that generated the response, as well as
information about the server’s technology stack.
Set-Cookie
The Set-Cookie header instructs the client to store a cookie with the specified name, value, and additional
attributes, such as expiration, domain, path, and security flags.
Content-Length
The Content-Length header, which specifies the size of the response body in bytes, can help the client anticipate
how much data it is going to receive.
23
Set request headers from an intuitive user interface: Users can easily set and adjust headers from within the
Headers tab of a request. Postman will also prompt you with common headers to help you automatically
complete your setup.
Save groups of commonly used request headers: Header presets allow users to keep commonly used headers
together, which can then be reused in other requests.
Leverage auto-generated request headers: Postman will automatically add certain headers to your request
according to its configuration. You can hover over any of these headers for additional information about why it
was included, as well as instructions for how to deactivate or override it.
View, edit, and capture cookies: Postman’s cookie manager enables users to easily keep track of the cookies
that are associated with various domains. Users can also capture cookies with the Postman proxy or Postman
Interceptor—and then use the cookies in the cookie jar when sending requests.
Safely store credentials: Users can set credentials in the Authorization tab—and add these credentials to the
Authorization request header. Postman provides support for several types of authorization, including API keys,
OAuth 2.0, and JWT.
View response headers: All response headers are displayed as key-value pairs under the Headers tab of the
response. Users can hover over any header’s information icon to learn more about it.
Header presets:
You can save commonly used headers together in a header preset. In the Headers tab of your request, select the Presets
dropdown list and choose Manage Presets. Select Add Header Preset to add a new preset, and enter a name for the
preset. Enter key-value pairs, then select Add.
You can select your preset in the Presets dropdown list. Selecting the preset will autopopulate the fields in your request
headers.
Autogenerated headers:
24
Postman will automatically add certain headers to your requests based on your request selections and settings. Select
hidden at the top of your request's Headers tab for information about what Postman will send with your request.
Hover over a header to view details about it. Postman will indicate why the header has been added. The details will also
indicate how to deactivate or override a header value if you need to.
Postman is a popular tool used by developers for testing APIs. When working with APIs in Postman, understanding
requests and responses is fundamental.
Request:
A request is an action you make to an API endpoint. It could be a GET request to fetch data, a POST request to submit
data, a PUT request to update data, or a DELETE request to remove data.
In Postman, you create requests by specifying the HTTP method (GET, POST, PUT, DELETE, etc.), the URL of the API
endpoint, request headers (optional), request body (optional, typically used with POST and PUT requests to send data),
and any query parameters (optional, for filtering or pagination).
After configuring the request, you can send it to the API server by clicking the "Send" button. Postman then sends the
request to the specified endpoint and waits for a response.
Response:
A response is the result returned by the API server after processing your request. It contains information such as status
code, headers, and optionally, a response body.
25
The status code indicates the success or failure of the request. For example, a status code in the 200 range (e.g., 200 OK)
typically indicates success, while a status code in the 400 or 500 range indicates an error.
Response headers provide metadata about the response, such as content type, server type, and caching directives.
The response body (if present) contains the actual data returned by the API server. This could be JSON, XML, HTML, or
any other format depending on the API.
In Postman, once the request is sent, you can view the response in the "Response" pane. Postman displays the status
code, headers, and response body (if available). This allows you to inspect the data returned by the API and verify if it
meets your expectations.
Collections are a bundle of requests. To create a collection, you can add an API call in the collection. You can reuse it in
your application. A lot of organizations offer collections. You can import this in your postman and test it. If you have
created a collection, you can export it or if you want the collection of others, you can import it.
Request URL: You will find a long-width bar in Postman where you will have to enter the URL to make the HTTP request.
Request Headers: In the request header, you enter the key value of the application. The two main key values are given
below.
Content-Type: The format of data is specified by Content-Type. Mainly developers use JSON format in the content type.
Authorization: This information is included to identify the requester.
Request Body: In Postman, you will get the tab of Body where you can mention some specific information that needs to
be sent with the request. You will get the option to send the data either in raw, binary, or any other form. Most of the
time you will select raw form. You will also get the option of Pre-request scripts. This gets executed before a request is
sent. In Postman, you are also allowed to write and run the test for each request. You can use JavaScript language for
this.
2. HTTP Response
26
Once you send the request to Postman, you get the response back from the API that contains Body, Cookies, Headers,
Tests, Status Code, and API Response time. Body and Header get organized in different tabs. Status code gets displayed
in another tab with the time taken to complete the API call. Some important status codes are given below to verify the
response.
27
28
29