0% found this document useful (0 votes)
8 views48 pages

WT U4 Call Back Functions 3may2024

The document discusses JavaScript functions, including their execution sequence, the concept of callbacks, and the use of arrow functions for shorter syntax. It also covers JSON, explaining its syntax, how to convert JSON to JavaScript objects, and provides examples of using JSON arrays. Additionally, it touches on HTTP headers, detailing their role in client-server communication and listing common request and response headers.

Uploaded by

supritaphotos225
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)
8 views48 pages

WT U4 Call Back Functions 3may2024

The document discusses JavaScript functions, including their execution sequence, the concept of callbacks, and the use of arrow functions for shorter syntax. It also covers JSON, explaining its syntax, how to convert JSON to JavaScript objects, and provides examples of using JSON arrays. Additionally, it touches on HTTP headers, detailing their role in client-server communication and listing common request and response headers.

Uploaded by

supritaphotos225
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/ 48

Callback and Arrow

functions, JSON
Function Sequence:

JavaScript functions are executed in the sequence they are called. Not in the
sequence they are defined.

This example will end up displaying "Goodbye":

function myFirst() {
<!DOCTYPE html> myDisplayer("Hello");
<html> }
<body> function mySecond() {
<h2>JavaScript Function Sequence</h2> myDisplayer("Goodbye");
<p>JavaScript functions are executed in the sequence they are }
called.</p> myFirst();
<p id="demo"></p> mySecond();
<script> </script>
function myDisplayer(some) { </body>
document.getElementById("demo").innerHTML = some; </html>
}

Sample I/O:
This example will end up displaying "Hello":

function myFirst() {
<!DOCTYPE html>
myDisplayer("Hello");
<html>
}
<body>
function mySecond() {
<h2>JavaScript Function Sequence</h2>
myDisplayer("Goodbye");
<p>JavaScript functions are executed in the sequence they are
}
called.</p>
mySecond();
<p id="demo"></p>
myFirst();
<script>
</script>
function myDisplayer(some) {
</body>
document.getElementById("demo").innerHTML = some;
</html>
}

Sample I/O:
Sequence Control : Example1
Sometimes you would like to have better control over when to execute a function.
Suppose you want to do a calculation and then display the result.

You could call a calculator function (myCalculator), save the result and then call another function (myDisplayer) to display the result:

<!DOCTYPE html> function myCalculator(num1, num2) {


<html> sum = num1 + num2;
<body> return sum;
}
<h2>JavaScript Functions</h2>
result = myCalculator(5, 5);
<p>Do a calculation and then display the result.</p> myDisplayer(result);
</script>
<p id="demo"></p>
</body>
<script> </html>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
Sample I/O:
Sequence Control : Example2
Or, you could call a calculator function (myCalculator) and let the calculator function call the display function (myDisplayer):

<!DOCTYPE html>
<html> function myCalculator(num1, num2) {
<body> sum = num1 + num2;
myDisplayer(sum);
<h2>JavaScript Callbacks</h2> }

<p>Do a calculation and then display the result.</p> myCalculator(5, 5);


</script>
<p id="demo"></p>
</body>
<script> </html>
function myDisplayer(some) {
document.getElementById("demo").innerHTML = some;
}
Sample I/O:
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> function myCalculator(num1, num2, myCallback) {


<html> sum = num1 + num2;
<body> myCallback(sum);
}
<h2>JavaScript Callbacks</h2>
myCalculator(5, 5, myDisplayer);
<p>Do a calculation and then display the result.</p> </script>

<p id="demo"></p> </body>


</html>
<script>
function myDisplayer(something) {
document.getElementById("demo").innerHTML = something;
}
Sample I/O:

In the example above, myDisplayer is the name of a function.

It is passed to myCalculator() as an argument.


Asynchronous Javascript: Sample I/O:
In the real world, callbacks are most often used with asynchronous functions.

A typical example is JavaScript setTimeout().

Waiting for a Timeout


When using the JavaScript function setTimeout(), you can specify a callback function to be executed on time-out:

Example:
<!DOCTYPE html> setTimeout(myFunction, 3000);
<html>
<body> function myFunction() {
document.getElementById("demo").innerHTML = “BMSCE !!";
<h2>JavaScript Callback</h2> }
</script>
<p>Wait 3 seconds (3000 milliseconds) for this page to
change.</p> </body>
</html>
<h1 id="demo"></h1> Where callbacks really shine are in asynchronous
functions, where one function has to wait for
<script> 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. Sample I/O:


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:
setTimeout(function() { myFunction(“BMS College !!!"); },
<!DOCTYPE html>
3000);
<html>
<body>
function myFunction(value) {
document.getElementById("demo").innerHTML = value;
<h2>JavaScript SetTimeout()</h2>
}
</script>
<p>Wait 3 seconds (3000 milliseconds) for this page to
change.</p>
</body>
</html>
<h1 id="demo"></h1>

<script>
Waiting for Intervals:
When using the JavaScript function setInterval(), you can specify a callback function to be executed for each interval:

Example

<!DOCTYPE html> function myFunction() {


<html> let d = new Date();
<body> document.getElementById("demo").innerHTML=
d.getHours() + ":" +
<h2>JavaScript setInterval()</h2> d.getMinutes() + ":" +
d.getSeconds();
<p>Using setInterval() to display the time every second (1000 }
milliseconds).</p> </script>

<h1 id="demo"></h1> </body>


</html>
Sample I/O:
<script>
setInterval(myFunction, 1000);
In the example above, myFunction is used as a callback.

myFunction is passed to setInterval() as an argument.

1000 is the number of milliseconds between intervals, so myFunction() will be called every second.
Arrow Functions
Arrow function
Example for Arrow function

Sample I/O:
Arrow functions allow us to write shorter function syntax:

<!DOCTYPE html> Sample I/O:


<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>
Before: With Arrow function:
<!DOCTYPE html> <!DOCTYPE html>
<html> <html>
<body> <body>

<h2>JavaScript Function</h2> <h2>JavaScript Arrow Function</h2>

<p>This example shows the syntax of a function, without the <p>This example shows the syntax of an Arrow Function, and
use of arrow function syntax.</p> how to use it.</p>

<p id="demo"></p> <p id="demo"></p>

<script> <script>
var hello; var hello;

hello = function() { hello = () => {


return "Hello World!"; return "Hello World!";
} }

document.getElementById("demo").innerHTML = hello(); document.getElementById("demo").innerHTML = hello();


</script> </script>

</body> </body>
</html> </html>
Sample I/O:

With Arrow function:


Before:
Arrow function:

Arrow functions allow us to write shorter function syntax:


myFunction = (a, b) => a * b;

Before:
hello = function() {
return "Hello World!";
}

With Arrow Function:


hello = () => {
return "Hello World!";
}
<!DOCTYPE html>
<html>
<body>

<h2>JavaScript Function</h2>

<p>This example shows the syntax of a function, without the


use of arrow function syntax.</p> Sample I/O:

<p id="demo"></p>

<script>
var hello;

hello = function() {
return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>
With Arrow function:
<!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> Sample I/O:

<p id="demo"></p>

<script>
var hello;

hello = () => {
return "Hello World!";
}

document.getElementById("demo").innerHTML = hello();
</script>

</body>
</html>
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:

Arrow Functions Return Value by Default:

<!DOCTYPE html> Sample I/O:


<html>
<body>
<h2>JavaScript Arrow Function</h2>
<p>This example shows an Arrow Function without the
brackets or the return keyword.</p>
<p id="demo"></p>
<script>
var hello;
hello = () => "Hello World!";
document.getElementById("demo").innerHTML = hello();
</script>
</body>
</html>
If you have parameters, you pass them inside the parentheses:

Arrow Function With Parameters:

<!DOCTYPE html>
Sample I/O:
<html>
<body>

<h2>JavaScript Arrow Function</h2>

<p>This example shows an Arrow Function with a parameter.</p>

<p id="demo"></p>

<script>
var hello;

hello = (val) => "Hello " + val;

document.getElementById("demo").innerHTML = hello("Universe!");
</script>

</body>
</html>
In fact, if you have only one parameter, you can skip the parentheses as well:

Arrow Function Without Parentheses:

<!DOCTYPE html> Sample I/O:


<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>
Sample I/O:

OR
Sample I/O:
11

We don’t need function.


As only one line in function body, we don’t need parenthesis.
As only one value, it is returned. We don’t need return statement also.
Convert these 4 functions into Arrow functions.
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.
JSON Syntax Rules:
•Data is in name/value pairs
•Data is separated by commas
•Curly braces hold objects
•Square brackets hold arrays
Note: JSON names require double quotes. JavaScript names do not.
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.

JSON arrays are written inside square brackets.


Just like in JavaScript, an array can contain objects:
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
In the example above, the object "employees" is an array. It contains three objects.
Each object is a record of a person (with a first name and a last name).
JSON Arrays Example Program:

<!DOCTYPE html>
<html>
Sample I/O:
<body> Ram
<p id="para"></p>
<script>
var jsonStringArray = {
// Assigned a JSON array of strings to the key "students".
"students": ["Ram", "Shyam", "Raksha",
"Akshay", "Prashant", "Varun“, ”Manju”],
};
// It returned an array. Then we accessed
// the first index of the array (which is "Ram") using [] syntax.
var x = jsonStringArray.students[0];

// Set the inner HTML of "para" paragraph to the value of variable "x".
document.getElementById("para").innerHTML = x;
</script>
</body>
</html>
Converting a JSON Text to a JavaScript Object

A common use of JSON is to read data from a web server, and display the data in a web page.

For simplicity, this can be demonstrated using a string as input.

First, create a JavaScript string containing JSON syntax:


let text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript
object:
const obj = JSON.parse(text);

Then, use the JavaScript built-in function JSON.parse() to convert the string into a JavaScript object:
const obj = JSON.parse(text);
Finally, use the new JavaScript object in your page:
use the new JavaScript object in your page:
Example:

<!DOCTYPE html> Sample I/O:


<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>
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.
most common HTTP headers

HTTP headers play a crucial role in server and client behavior throughout the
request and response cycle. Request headers are sent by the client to the
server and contain information and instructions related to the requested
resource, while response headers are sent by the server to the client and
provide metadata, instructions, and additional information about the response
itself.
Some of most commonly used request headers are as given below:
• Accept
• User-Agent
• Authorization
• Content-type
• Cookie

The most common response headers are:


• Content-type
• Cache-control
• Server
• Set-cookie
• Content-length
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.
HTTP status codes

HTTP status codes are three-digit codes that indicate the outcome of
an API request. They are included in the API’s response to the API client
and they include important information that helps the client know how to
proceed.

HTTP status codes are essential to the HTTP protocol, which defines
how data is transferred between clients and servers on the internet.
Anyone who works with web-based technologies should have a solid
understanding of these codes, as they provide valuable insight that can
be used to troubleshoot issues and improve the user experience.
different types of HTTP status codes

HTTP status codes are grouped into five classes, each


beginning with a number that represents the type of
response. The classes are:
• 1xx informational responses
• 2xx success responses
• 3xx redirection responses
• 4xx client error responses
• 5xx server error responses

You might also like