Skip to main content

Introduction to Javascript, data types, varibles and if-else conditions

JSON​

  • JSON stands for JavaScript Object Notation. It is used to store and exchange data.

Accessing Data from JSON​

  • If you have a JavaScript object, you can access data using:
const user = {
name: 'Alice',
age: 25,
}

console.log(user.name) // Alice
console.log(user['age']) // 25

JSON.parse() Method​

  • JSON.parse() is used to convert a JSON string into a JavaScript object.
const jsonData = '{"name":"Bob","age":30}'

const obj = JSON.parse(jsonData) // converts to JavaScript object
console.log(obj) // {name: 'Bob', age: 30}
console.log(obj.name) // Bob
console.log(obj.age) // 30

JSON.stringify() Method​

  • JSON.stringify() is used to convert a JavaScript object into a JSON string.

const obj = {
name: "Charlie",
age: 28
};

const jsonString = JSON.stringify(obj);

console.log(jsonString); // {"name":"Charlie","age":28}

fetch​

  • fetch data from server.

Get Request​

async function getPost() {
try {
const response = await fetch('https://jsonplaceholder.typicode.com/posts/1');
const data = await response.json();
console.log(data);
} catch (error) {
console.error('Error:', error);
}
}

getPost();

// {userId: 1, id: 1, title: 'sunt aut facere repellat provident occaecati excepturi optio reprehenderit', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}

post​

  • send data to the server.
fetch('https://jsonplaceholder.typicode.com/posts', {
method: 'POST',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Hello World',
body: 'This is a test post',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('POST Success:', data))
.catch(error => console.error('Error:', error));

// POST Success: {title: 'Hello World', body: 'This is a test post', userId: 1, id: 101}

put​

  • Update Data Fully
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PUT',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
id: 1,
title: 'Updated Title',
body: 'Updated body content',
userId: 1
})
})
.then(response => response.json())
.then(data => console.log('PUT Success:', data))
.catch(error => console.error('Error:', error));

// PUT Success: {id: 1, title: 'Updated Title', body: 'Updated body content', userId: 1}

patch​

  • Update Data Partially.
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'PATCH',
headers: {
'Content-Type': 'application/json'
},
body: JSON.stringify({
title: 'Only Title Updated'
})
})
.then(response => response.json())
.then(data => console.log('PATCH Success:', data))
.catch(error => console.error('Error:', error));

// PATCH Success: {userId: 1, id: 1, title: 'Only Title Updated', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}

delete​

  • Remove Data
fetch('https://jsonplaceholder.typicode.com/posts/1', {
method: 'DELETE'
})
.then(response => {
if (response.ok) {
console.log('DELETE Success');
} else {
console.error('Delete Failed');
}
})
.catch(error => console.error('Error:', error));

// DELETE Success

summary

MethodPurposeRequires Body?Typical Use
GETFetch data❌ NoRead-only data
POSTCreate new data✅ YesRegister, Create
PUTReplace existing✅ YesFull update
PATCHUpdate part of data✅ YesUpdate specific fields
DELETERemove data❌ OptionalDelete an item

HTTP Status Codes

CodeTypeStatusDescription
1001xx InfoContinueRequest received, client can continue sending the rest.
1011xx InfoSwitching ProtocolsProtocol switch request accepted (e.g., to WebSocket).
2002xx SuccessOKStandard response for a successful request.
2012xx SuccessCreatedRequest successful, and a new resource was created.
2022xx SuccessAcceptedRequest accepted, processing is not yet complete.
2042xx SuccessNo ContentSuccess, but no data returned.
2062xx SuccessPartial ContentPartial data (useful for range requests).
3013xx RedirectMoved PermanentlyResource has been permanently moved to a new URI.
3023xx RedirectFoundTemporarily redirected to a different URI.
3043xx RedirectNot ModifiedResource has not changed (use cached version).
3073xx RedirectTemporary RedirectRedirect with same method (e.g., POST remains POST).
3083xx RedirectPermanent RedirectRedirect with same method permanently.
4004xx ClientBad RequestClient sent invalid or incomplete request.
4014xx ClientUnauthorizedRequest lacks valid authentication credentials.
4034xx ClientForbiddenAuthenticated but not allowed to access the resource.
4044xx ClientNot FoundResource or endpoint doesn’t exist.
4054xx ClientMethod Not AllowedHTTP method (e.g., PUT/DELETE) not supported for this resource.
4084xx ClientRequest TimeoutServer timed out waiting for the request.
4094xx ClientConflictRequest could not be completed due to conflict (e.g., duplicate data).
4224xx ClientUnprocessable EntityRequest is well-formed but contains semantic errors (e.g., validation fail).
4294xx ClientToo Many RequestsClient has sent too many requests in a given time (rate limiting).
5005xx ServerInternal Server ErrorGeneral server error; something went wrong on the server side.
5015xx ServerNot ImplementedServer does not recognize or support the request method.
5025xx ServerBad GatewayServer received an invalid response from the upstream server.
5035xx ServerService UnavailableServer is overloaded or down for maintenance.
5045xx ServerGateway TimeoutUpstream server failed to respond in time.

What is a Query String?​

  • A query string is the part of a URL that passes data to the server. It starts with ? and has key-value pairs separated by &.

How to Create a Query String ?​

Manually const url = "https://example.com/search?name=John&age=25";

Using URLSearchParams

const params = new URLSearchParams({
name: 'John',
age: 25,
city: 'Delhi',
})
const url = `https://example.com/profile?${params.toString()}`
console.log(url) // https://example.com/profile?name=John&age=25&city=Delhi

How to Read Query Strings in JavaScript ?​

// const url = new URL(window.location.href)
const url = new URL('https://example.com/profile?name=John&age=25&city=Delhi')

const params = new URLSearchParams(url.search)
console.log(params)

console.log(params.get("name")); // Output: "John"
console.log(params.get("age")); // Output: "25"

Axios​

  • Axios is a promise-based HTTP client for the browser and Node.js. It’s used to send GET, POST, PUT, DELETE, etc., requests to APIs.
  • npm install axios
  • CDN - <script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Axios Test</title>
</head>
<body style="background-color: rgb(53, 52, 52); color: white;">

<h1>Axios Test</h1>

<!-- Load Axios from CDN -->
<script src="https://cdn.jsdelivr.net/npm/axios/dist/axios.min.js"></script>

<!-- Then load your own script -->
<script src="script.js"></script>

</body>
</html>

GET Request​

axios
.get('https://jsonplaceholder.typicode.com/users/1')
.then((response) => {
console.log(response.data) // Output the data
})
.catch((error) => {
console.error(error)
})
// {id: 1, name: 'Leanne Graham', username: 'Bret', email: 'Sincere@april.biz', address: {…}, …}

POST Request​

axios
.post('https://jsonplaceholder.typicode.com/posts', {
title: 'Hello',
body: 'This is a post',
userId: 1,
})
.then((response) => {
console.log(response.data)
})
.catch((error) => {
console.error(error)
})

// {title: 'Hello', body: 'This is a post', userId: 1, id: 101}

PUT Request​

axios.put('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated title',
body: 'Updated body',
userId: 1
})
.then(response => console.log(response.data))
.catch(error => console.error(error));

// {title: 'Updated title', body: 'Updated body', userId: 1, id: 1}

DELETE Request​

axios.delete('https://jsonplaceholder.typicode.com/posts/1')
.then(response => console.log('Deleted'))
.catch(error => console.error(error));

// Deleted

PATCH Request​

axios.patch('https://jsonplaceholder.typicode.com/posts/1', {
title: 'Updated Title Only'
})
.then(response => {
console.log('Patch Response:', response.data);
})
.catch(error => {
console.error('Error:', error);
});

// Patch Response: {userId: 1, id: 1, title: 'Updated Title Only', body: 'quia et suscipit\nsuscipit recusandae consequuntur …strum rerum est autem sunt rem eveniet architecto'}

Sending Headers​

axios
.get('https://jsonplaceholder.typicode.com/posts/1', {
headers: {
Authorization: 'Bearer YOUR_TOKEN',
'Content-Type': 'application/json',
},
})
.then((res) => console.log(res.data))
.catch((err) => console.error(err))

Handling Query Parameters​

axios.get('https://jsonplaceholder.typicode.com/posts/1', {
params: {
query: 'books',
page: 2
}
})
.then(res => console.log(res.data))
.catch(err => console.error(err));

What is the use of Content-Type header?

  • The Content-Type header tells the server what kind of data you are sending in the body of the HTTP request.
headers: {
'Content-Type': 'application/json'
}
  • The request body contains JSON data.
  • So the server knows to parse the body as JSON.

Why is this important?

  • If the server expects JSON but you don’t set Content-Type: application/json, it might fail to parse the request body correctly.
  • For example, if you send data as JSON without this header, the server may think it’s plain text or some other format and reject or misinterpret it.

Difference b/w fetch and Axios

Featurefetchaxios
What is it?Native browser API for making HTTP requestsThird-party library built on top of XMLHttpRequest (XHR)
InstallationNo installation needed (built-in in modern browsers)Requires installation (npm install axios)
Browser supportSupported in modern browsers, older browsers need polyfillWorks on most browsers including older ones
SyntaxUses native Promises, simple but requires manual JSON parsingUses Promises, automatically parses JSON responses
Response parsingYou manually parse with .json(), .text(), etc.Response data is automatically parsed (response.data)
Error handlingOnly rejects on network failure, not on HTTP errorsRejects on HTTP error status codes (like 404, 500)
Request cancellationSupported via AbortControllerSupports cancellation with CancelToken
InterceptorsNot supportedSupports request and response interceptors (middleware)
Request timeoutNo built-in supportBuilt-in timeout support
Automatic transformsNoneSupports request/response transformation
Uploading/downloading progressNot supported directlySupports progress tracking
JSON handlingYou manually call .json() on responseAutomatically serializes JS objects to JSON and parses JSON
ConvenienceBasic, flexible but needs more code for common tasksMore features out of the box, easier for complex requests