Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
152 views

FSD Unit2

Uploaded by

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

FSD Unit2

Uploaded by

Bhagya
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 41

UNIT - II

Frontend Development: Javascript basics OOPS Aspects of JavaScript


Memory usage and Functions in JS AJAX for data exchange with server
jQuery Framework jQuery events, UI components etc. JSON data format.
Frontend Development : Javascript basics
Learn JavaScript Tutorial

Our JavaScript Tutorial is designed for beginners and professionals both. JavaScript is usedto
create client-side dynamic pages.
JavaScript is an object-based scripting language which is lightweight and cross-platform.
JavaScript is not a compiled language, but it is a translated language. The JavaScript Translator
(embedded in the browser) is responsible for translating the JavaScript code forthe web browser.

What is JavaScript

JavaScript (js) is a light-weight object-oriented programming language which is used by several


websites for scripting the webpages. It is an interpreted, full-fledged programming language that
enables dynamic interactivity on websites when applied to an HTML document. It was
introduced in the year 1995 for adding programs to the webpages in the Netscape Navigator
browser. Since then, it has been adopted by all other graphical web browsers. With JavaScript,
users can build modern web applications to interact directly without reloading the page every
time. The traditional website uses js to provide several forms of interactivity and simplicity.

Although, JavaScript has no connectivity with Java programming language. The name was
suggested and provided in the times when Java was gaining popularity in the market. In addition to
web browsers, databases such as CouchDB and MongoDB uses JavaScript as theirscripting and
query language.

Features of JavaScript

There are following features of JavaScript:

1. All popular web browsers support JavaScript as they provide built-in execution environments.
2. JavaScript follows the syntax and structure of the C programming language. Thus, it is a
structured programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending onthe
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather than using
classes for inheritance.
5. It is a light-weighted and interpreted language.
6. It is a case-sensitive language.
7. JavaScript is supportable in several operating systems including, Windows, macOS, etc.
8. It provides good control to the users over the web browsers.

1
History of JavaScript

In 1993, Mosaic, the first popular web browser, came into existence. In the year 1994, Netscape
was founded by Marc Andreessen. He realized that the web needed to become more dynamic.
Thus, a 'glue language' was believed to be provided to HTML to make web designing easy for
designers and part-time programmers. Consequently, in 1995, the company recruited Brendan
Eich intending to implement and embed Scheme programming language to the browser. But,
before Brendan could start, the company merged with Sun Microsystems for adding Java into its
Navigator so that it could compete with Microsoft overthe web technologies and platforms. Now,
two languages were there: Java and the scripting language. Further, Netscape decided to give a
similar name to the scripting language as Java's. It led to 'Javascript'. Finally, in May 1995, Marc
Andreessen coined the first code of Javascript named 'Mocha'. Later, the marketing team replaced
the name with 'LiveScript'.
But, due to trademark reasons and certain other reasons, in December 1995, the language was
finally renamed to 'JavaScript'. From then, JavaScript came into existence.

Application of JavaScript

JavaScript is used to create interactive websites. It is mainly used for:

 Client-side validation,
 Dynamic drop-down menus,
 Displaying date and time,
 Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog boxand
prompt dialog box),
 Displaying clocks etc.

JavaScript Example

<script>
document.write("Hello JavaScript by JavaScript");
</script>
JavaScript Example

Javascript example is easy to code. JavaScript provides 3 places to put the JavaScript code:
within body tag, within head tag and external JavaScript file.

Let’s create the first JavaScript example.

<script type="text/javascript">
document.write("JavaScript is a simple language for javatpoint learners");
</script>
The script tag specifies that we are using JavaScript.
The text/javascript is the content type that provides information to the browser about the data.
The document.write() function is used to display dynamic content through JavaScript.

3 Places to put JavaScript code

1. Between the body tag of html


2. Between the head tag of html
3. In .js file (external javaScript)

2
JavaScript Example : code between the body tag
In the above example, we have displayed the dynamic content using JavaScript. Let’s see thesimple
example of JavaScript that displays alert dialog box.

1. <script type="text/javascript">
2. alert("Hello Javatpoint");
3. </script>
JavaScript Example : code between the head tag
Let’s see the same example of displaying alert dialog box of JavaScript that is contained inside
the head tag.

In this example, we are creating a function msg(). To create function in JavaScript, you needto
write function with function_name as given below.

To call function, you need to work on event. Here we are using onclick event to call msg() function.

1. <html>
2. <head>
3. <script type="text/javascript">
4. function msg(){
5. alert("Hello Javatpoint");6.
}
6. </script>
7. </head>
8. <body>
9. <p>Welcome to JavaScript</p>
10. <form>
11. <input type="button" value="click" onclick="msg()"/>
12. </form>
13. </body>
14. </html>

External JavaScript file

We can create external JavaScript file and embed it in many html page.

It provides code re usability because single JavaScript file can be used in several html pages.

An external JavaScript file must be saved by .js extension. It is recommended to embed allJavaScript
files into a single file. It increases the speed of the webpage.

Let's create an external JavaScript file that prints Hello Javatpoint in a alert dialog box.

message.js
1. function msg(){
2. alert("Hello Javatpoint");3. }

Let's include the JavaScript file into html page. It calls the JavaScript function on buttonclick.

index.html

1. <html>
3
2. <head>
3. <script type="text/javascript" src="message.js"></script>
4. </head>
5. <body>
6. <p>Welcome to JavaScript</p>
7. <form>
8. <input type="button" value="click" onclick="msg()"/>
9. </form>
10. </body>
11. </html>

Advantages of External JavaScript


There will be following benefits if a user creates an external javascript:

1. It helps in the reusability of code in more than one HTML file.


2. It allows easy code readability.
3. It is time-efficient as web browsers cache the external js files, which further reducesthe
page loading time.
4. It enables both web designers and coders to work with html and js files parallelly and
separately, i.e., without facing any code conflictions.
5. The length of the code reduces as only we need to specify the location of the js file.

Disadvantages of External JavaScript

There are the following disadvantages of external files:

1. The stealer may download the coder's code using the url of the js file.
2. If two js files are dependent on one another, then a failure in one file may affect the
execution of the other dependent file.
3. The web browser needs to make an additional http request to get the js code.
4. A tiny to a large change in the js code may cause unexpected results in all its
dependent files.
5. We need to check each file that depends on the commonly created external javascript file.
6. If it is a few lines of code, then better to implement the internal javascript code.
JavaScript Comment

1. JavaScript comments
2. Advantage of javaScript comments
3. Single-line and Multi-line comments

The JavaScript comments are meaningful way to deliver message. It is used to add information
about the code, warnings or suggestions so that end user can easily interpret thecode.

The JavaScript comment is ignored by the JavaScript engine i.e. embedded in the browser.

Advantages of JavaScript comments

There are mainly two advantages of JavaScript comments.

1. To make code easy to understand It can be used to elaborate the code so that end user can easily
understand the code.
2. To avoid the unnecessary code It can also be used to avoid the code being executed. Sometimes,

4
we add the code to perform some action. But after sometime, there may be needto disable the code.
In such case, it is better to use comments.
Types of JavaScript Comments

There are two types of comments in JavaScript.

1. Single-line Comment
2. Multi-line Comment

JavaScript Single line Comment

It is represented by double forward slashes (//). It can be used before and after the statement. Let’s
see the example of single-line comment i.e. added before the statement.
1. <script>
2. // It is single line comment
3. document.write("hello javascript");
4. </script>
Let’s see the example of single-line comment i.e. added after the statement.

1. <script>
2. var a=10;
3. var b=20;
4. var c=a+b;//It adds values of a and b variable
5. document.write(c);//prints sum of 10 and 20
6. </script>

JavaScript Multi line Comment

It can be used to add single as well as multi line comments. So, it is more convenient.

It is represented by forward slash with asterisk then asterisk with forward slash. For example:

1. /* your code here */

It can be used before, after and middle of the statement.

1. <script>
2. /* It is multi line comment.
3. It will not be displayed */
4. document.write("example of javascript multiline comment");
5. </script>
JavaScript Variable

A JavaScript variable is simply a name of storage location. There are two types of variables in
JavaScript : local variable and global variable.

There are some rules while declaring a JavaScript variable (also known as identifiers).

1. Name must start with a letter (a to z or A to Z), underscore( _ ), or dollar( $ ) sign.


2. After first letter we can use digits (0 to 9), for example value1.
3. JavaScript variables are case sensitive, for example x and X are different variables.
Correct JavaScript variables

5
1. var x = 10;
2. var _value="sonoo";

Incorrect JavaScript variables

1. var 123=30;
2. var *aa=320;

Example of JavaScript variable

Let’s see a simple example of JavaScript variable.

1. <script>
2. var x = 10;
3. var y = 20;
4. var z=x+y;
5. document.write(z);
6. </script>

Output of the above example

30

JavaScript local variable


A JavaScript local variable is declared inside block or function. It is accessible within the
function or block only. For example:

<script>
function abc(){
var x=10;//local variable
}
</script>

<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>

JavaScript global variable


A JavaScript global variable is accessible from any function. A variable i.e. declaredoutside
the function or declared with window object is known as global variable. For example:

1. <script>
2. var data=200;//gloabal variable
3. function a(){
4. document.writeln(data);
5. }

6. function b(){
7. document.writeln(data);
6
8. }
9. a();//calling JavaScript function
10. b();
11. </script>

JavaScript Global Variable

A JavaScript global variable is declared outside the function or declared with window
object. It can be accessed from any function.
Let’s see the simple example of global variable in JavaScript.

1. <script>
2. var value=50;//global variable
3. function a(){
4. alert(value);
5. }
6. function b(){
7. alert(value);
8. }
9. </script>

Declaring JavaScript global variable within function

To declare JavaScript global variables inside function, you need to use window object.
For example:

1. window.value=90;

Now it can be declared inside any function and can be accessed from any function. For example:

4. function m(){
5. window.value=100;//declaring global variable by window object
6. }
7. function n(){
8. alert(window.value);//accessing global variable from other function
6. }

Internals of global variable in JavaScript

When you declare a variable outside the function, it is added in the window object internally. You can
access it through window object also. For example:

1. var value=50;
2. function a(){
3. alert(window.value);//accessing global variable
4. }

OOPS ASPECTS IN JAVASCRIPT

What Is Object-oriented Programming?


Object-oriented Programming treats data as a crucial element in program development and doesn't
allow it to flow freely around the system. It ties data more securely to the function that operates on
7
it and protects it from accidental modification from an outside function. OOP breaks down a
problem into several entities called objects and builds data and functions around these objects.
Basic concepts of Object-oriented Programming

Objects

Objects are the basic run-time bodies in an object-oriented framework. They may represent a place,
a person, an account, a table of data, or anything that the program needs to handle.
Objects can also represent user-defined data such as vectors, time, and lists.

Consider two objects, “customer” and “account” in a program. The customer object may senda
message requesting the bank balance.

Classes

We know that objects hold the data and the functions to manipulate the data. However, the two
can be bound together in a user-defined data type with the help of classes. Any numberof objects
can be created in a class. Each object is associated with the data of type class. A class is therefore
a collection of objects of similar types.

For example, consider the class “Fruits”. We can create multiple objects for this class -Fruit
Mango;
This will create an object mango belonging to the class fruit.
Encapsulation
Encapsulation is the wrapping up/binding of data and function into a single unit called class. Data
encapsulation is the most prominent feature of a class wherein the data is not accessibleto the
outside world, and only those functions wrapped inside the class can access it. These functions
serve as the interface between the object’s data and the program.

Inheritance
The phenomenon where objects of one class acquire the properties of objects of another class is
called Inheritance. It supports the concept of hierarchical classification. Consider the object “car”
that falls in the class “Vehicles” and “Light Weight Vehicles”.

In OOP, the concept of inheritance ensures reusability. This means that additional features can
be added to an existing class without modifying it. This is made possible by deriving a new class
from the existing one.
OOP Concepts in JavaScript

JavaScript Objects
In JavaScript, almost "everything" is an object.

 Booleans can be objects (if defined with the new keyword)


 Numbers can be objects (if defined with the new keyword)
 Strings can be objects (if defined with the new keyword)
 Dates are always objects
 Maths are always objects
 Regular expressions are always objects
 Arrays are always objects
 Functions are always objects
 Objects are always objects
8
All JavaScript values, except primitives, are objects.

Objects are Variables


JavaScript variables can contain single values:

Example
let person = "John Doe";

JavaScript variables can also contain many values.

Objects are variables too. But objects can contain many values.

Object values are written as name : value pairs (name and value separated by a colon).

Example
let person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

A JavaScript object is a collection of named values

It is a common practice to declare objects with the const keyword.

Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

Object Properties
The named values, in JavaScript objects, are called properties.

Properties Values
firstName John
lastName Doe
age 20
eyeColor blue

Objects written as name value pairs are similar to:

 Associative arrays in PHP


 Dictionaries in Python
 Hash tables in C
 Hash maps in Java
 Hashes in Ruby and Perl

Object Methods
 Methods are actions that can be performed on objects.
 Object properties can be both primitive values, other objects, and functions.
 An object method is an object property containing a function definition.
Properties Values
firstName John
lastName Doe
age 20
eyeColor blue
9
fullName function() {return this.firstName + " " +
this.lastName;}

Creating a JavaScript Object


With JavaScript, you can define and create your own objects.

There are different ways to create new objects:

 Create a single object, using an object literal.


 Create a single object, with the keyword new.
 Define an object constructor, and then create objects of the constructed type.
 Create an object using Object.create().

Using an Object Literal


 This is the easiest way to create a JavaScript Object.
 Using an object literal, you both define and create an object in one statement.
 An object literal is a list of name:value pairs (like age:50) inside curly braces {}.

The following example creates a new JavaScript object with four properties:
Example
const person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

This section will show how JavaScript implements them.

Creating Objects in JavaScript

 We can create an object using the string literal in JavaScript.

var student = {
name: "pp", age:
21,
studies: "Computer Science",
};

document.getElementById("demo").innerHTML = student.name + " of the age " +


student.age + " studies " + student.studies;

 Creating objects using the new keyword.

var student = new Object();


student.name = "pp",
student.age=21,
student.studies = "Computer Science";

document.getElementById("demo").innerHTML = student.name + " of the age " +student.age + "


studies " + student.studies;

 Creating an object using the object constructor.

function stud(name, age, studies){


this.name = name;
10
this.age = age;
this.studies = studies;
}
var student = stud("Chris", 21, "Computer Science");

document.getElementById("demo").innerHTML = student.name + " of the age " +

student.age + " studies " + student.studies;

What is this?
In JavaScript, the this keyword refers to an object.

Which object depends on how this is being invoked (used or called).

The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.

Note
this is not a variable. It is a keyword. You cannot change the value of this.

Class Implementation in JavaScript

ECMAScript 2015, also known as ES6, introduced JavaScript Classes.

JavaScript Classes are templates for JavaScript Objects.

JavaScript Class Syntax


Use the keyword class to create a class.

Always add a method named constructor():

Syntax
class ClassName {
constructor() { ... }
}

Example

11
class Car {
constructor(name, year) {
this.name = name;
this.year = year;
}
}

The example above creates a class named "Car".

The class has two initial properties: "name" and "year".

A JavaScript class is not an object.

It is a template for JavaScript objects.

Using a Class
When you have a class, you can use the class to create objects:

Example
const myCar1 = new Car("Ford", 2014);
const myCar2 = new Car("Audi", 2019);

The example above uses the Car class to create two Car objects.

The constructor method is called automatically when a new object is created.

The Constructor Method


The constructor method is a special method:

 It has to have the exact name "constructor"


 It is executed automatically when a new object is created
 It is used to initialize object properties

If you do not define a constructor method, JavaScript will add an empty constructor method.

Class Methods
Class methods are created with the same syntax as object methods.
Use the keyword class to create a class.
Always add a constructor() method.
Then add any number of methods.
Syntax
class ClassName {
constructor() { ... }
method_1() { ... }
method_2() { ... }
method_3() { ... }
}

Consider the following example.


class Cars {
constructor(name, maker, price) {
12
this.name = name;
this.maker = maker;
this.price = price;
}
getDetails(){

return (`The name of the car is ${this.name}.`)

}
}

let car1 = new Cars('Rolls Royce Ghost', 'Rolls Royce', '$315K'); let car2 =
new Cars('Mercedes AMG One', 'Mercedes', '$2700K');
console.log(car1.name);
console.log(car2.maker);
console.log(car1.getDetails());

Encapsulation in JavaScript

Encapsulation includes wrapping the property and the function within a single unit. Consider the
following example:

Class Emp_details{
constructor(name,id){
this.name = name;
this.id = id;
}

add_Address(add){
this.add = add;
}

getDetails(){

console.log(`Employee Name: ${this.name}, Address: ${this.add}`);

let person1 = new Emp_details('Anand',27);


person1.add_Address('Bangalore');
person1.getDetails();
Here, the class holds the data variables name and id along with the functions add_Address and
getDetails. All are encapsulated within the class Emp_details.

Class Inheritance
To create a class inheritance, use the extends keyword.

A class created with a class inheritance inherits all the methods from another class:

13
Example
Create a class named "Model" which will inherit the methods from the "Car" class:

class Car {
constructor(brand) {
this.carname = brand;
}
present() {
return 'I have a ' + this.carname;
}
}

class Model extends Car {


constructor(brand, mod) {
super(brand);
this.model = mod;
}
show() {
return this.present() + ', it is a ' + this.model;
}
}

let myCar = new Model("Ford", "Mustang");


document.getElementById("demo").innerHTML = myCar.show();

The super() method refers to the parent class.

By calling the super() method in the constructor method, we call the parent's constructor method and gets
access to the parent's properties and methods.

Inheritance is useful for code reusability: reuse properties and methods of an existing class when you create
a new class.

Memory Management in JavaScript

Memory management is an essential task when writing a good and effective program in some
programming languages. This article will help you to understand different concepts of memory
management in JavaScript. In low-level languages like C and C++, programmers should care about
the usage of memory in some manual fashion. On the other hand, Javascript automatically allocates
memory when objects are created into the environment andalso it cleans the memory when an object
is destroyed. JavaScript can manage all of these on its own but this does not imply that the
developers do not need to worry about the memory management in JavaScript.

Memory management in any programming language involves three important phases, termedas
memory life-cycle −

 Allocating the memory which is required in our program.


 Utilize the allocated memory unit.
 After completion, clear the memory block.

JavaScript engines have two places to store data:

14
 Stack: It is a data structure used to store static data. Static data refers to data whose size is
known by the engine during compile time. In JavaScript, static data includes primitive values
like strings, numbers, boolean, null, and undefined. References that point to objects and
functions are also included. A fixed amount of memory is allocated for static data. This process
is known as static memory allocation.
 Heap: It is used to store objects and functions in JavaScript. The engine doesn’t allocate a
fixed amount of memory. Instead, it allocates more space as required.

Overview:

Stack Heap

Primitive data types and references Objects and functions

Size is known at compile time Size is known at run time

Fixed memory allocated No limit for object memory

Example:
Javascript

const employee = {
name: 'Rajesh',
age: 30,
};
const name="Ram"

// Allocates memory for object in heap.


// Values in object are primitive,which is why they
// are stored in stack.

function getname(name) {
return name;
}
// The function return value is given to stack after
// being evaluated in the heap

const newEmployee = employee;

/* The newEmployee object will be stored in the stack and it will refer to the employee
object in heap */

Explanation: In the above example object ’employee’ is created in the heap and a reference to it in
the stack.

15
Memory Management in JavaScript
Different Strategies to Allocate Memory in JavaScript

Allocation in JavaScript

Value initialization
In order to not bother the programmer with allocations, JavaScript will automatically allocate
memory when values are initially declared.

var n = 374; // allocates memory for a number


var s = 'sessionstack'; // allocates memory for a string var o = {
a: 1,
b: null
}; // allocates memory for an object and its contained values
var a = [1, null, 'str']; // (like object) allocates memory for the
// array and its contained values
function f(a) {
return a + 3;
} // allocates a function (which is a callable object)
// function expressions also allocate an object
someElement.addEventListener('click', function() {
someElement.style.backgroundColor = 'blue';
}, false);
Allocation via function calls
Some function calls result in object allocation.

var s1 = 'sessionstack';
var s2 = s1.substr(0, 3); // s2 is a new string
// Since strings are immutable,
// JavaScript may decide to not allocate memory,
// but just store the [0, 3] range.var a1 = ['str1', 'str2'];
var a2 = ['str3', 'str4'];
var a3 = a1.concat(a2);

16
// new array with 4 elements being
// the concatenation of a1 and a2 elements
Using memory in JavaScript
Using the allocated memory in JavaScript basically, means reading and writing in it.
This can be done by reading or writing the value of a variable or an object property or even passing an
argument to a function.
Release when the memory is not needed anymore
 Most of the memory management issues come at this stage.
 The hardest task here is to figure out when the allocated memory is not needed any longer. It
often requires the developer to determine where in the program such piece of memory is not
needed anymore and free it.
 High-level languages embed a piece of software called garbage collector which job is to track
memory allocation and use in order to find when a piece of allocated memory is not needed
any longer in which case, it will automatically free it.
 Unfortunately, this process is an approximation since the general problem of knowing whether
some piece of memory is needed is undecidable (can’t be solved by an algorithm).
 Most garbage collectors work by collecting memory which can no longer be accessed, e.g. all
variables pointing to it went out of scope. That’s, however, an under-approximation of the set
of memory spaces that can be collected, because at any point a memory location may still have
a variable pointing to it in scope, yet it will never be accessed again.
Garbage Collection: Garbage collectors are used in releasing memory. Once the engine
recognizes that a variable, object, or function is not needed anymore, it releases the memory it
occupied. The main issue here is that it is very difficult to predict accurately whether a particular
variable, object, or function is needed anymore or not. Some algorithms help to find the moment
when they become obsolete with great precision.

References

The main concept that garbage collection algorithms rely on is the concept of reference. Within the
context of memory management, an object is said to reference another object if the former has access
to the latter (either implicitly or explicitly). For instance, a JavaScript object has a reference to
its prototype (implicit reference) and to its properties values (explicit reference).
In this context, the notion of an "object" is extended to something broader than regular JavaScript
objects and also contain function scopes (or the global lexical scope).

Reference-counting garbage collection: It frees the memory allocated to the objects that have no
references pointing to them. However, the problem with this algorithm is that it doesn’t understand
cyclic references.

Example: Javascript

let game = {
name: 'cricket',
};
let boy = {
name: 'Ram',
}
game.boy = boy;
boy.game = game;
boy = null;
game = null;

17
Explanation: In this example, the game and boy both reference each other. Thus, the algorithm
won’t release the allocated memory. Setting them to null won’t make the algorithm realize that
they can’t be used anymore, leading to no release of allocated memory.
Mark-and-sweep algorithm: This algorithm solves the above-mentioned issue. Instead of finding
references to a particular object, it detects if they are reachable from the root object.
Note: In JavaScript root is the window object while in NodeJS it is the global object.
The algorithm marks objects that are not reachable as garbage and collects (sweeps) them. Thus, it
is known as Mark and Sweep algorithm. In the previous example, neither the game nor the boy
object can be accessed from the root object. Thus, it is marked as garbage and collected afterwards.

Using previously Allocated Memory in JavaScript

Using previously allocated memory is just reading or writing values from some variables which are
assigned previously. We can update its existing value with some other values.

Deallocating memory blocks in JavaScript

When our purpose is served, we can remove the allocated memory block. In some low-level
languages, this is a necessary step, otherwise, it may occupy memory spaces over time and the total
system may crash. JavaScript also has native support of Garbage Collector, which cleans
unnecessary memory blocks and cleans up the memory. But sometimes the compiler cannot
understand whether a block will be used in later cases or not. In such cases, the Garbage Collector
does not clean up that memory. To manually remove allocated locations, we can use the ‘delete’
keyword before the variable name.

Syntax

delete <variable_name>
const Employee = {
firstname: 'John',
lastname: 'Doe',
};
console.log(Employee.firstname);
// Expected output: "John"

18
delete Employee.firstname;
console.log(Employee.firstname);
// Expected output: undefined

The variable must be allocated beforehand, otherwise, it will raise an error while trying to delete
that variable.
Note − The ‘delete’ keyword will only work when the variable is allocated directly (without using the
var or let keyword).

Conclusion

Working with any programming language, the programmer should know the overall concept in depth.
Memory management is one of the concerning issues, in which developers should properly manage
the memory otherwise it will occupy unnecessary memory blocks and createmajor problems in the
environment. JavaScript provides an additional garbage collector tool that automatically cleans the
unused memory blocks. However, we can also deallocate memory by using the ‘delete’ keyword just
before the variable name

AJAX for data exchange with server


Short Description of AJAX

AJAX = Asynchronous JavaScript And XML.


AJAX is not a programming language.
AJAX just uses a combination of:

 A browser built-in XMLHttpRequest object (to request data from a web server)
 JavaScript and HTML DOM (to display or use the data)

AJAX allows web pages to be updated asynchronously by exchanging data with a web server behind the
scenes

 Update a web page without reloading the page


 Request data from a server - after the page has loaded
 Receive data from a server - after the page has loaded
 Send data to a server - in the background

How AJAX Works

19
1. An event occurs in a web page (the page is loaded, a button is clicked)
2. An XMLHttpRequest object is created by JavaScript
3. The XMLHttpRequest object sends a request to a web server
4. The server processes the request
5. The server sends a response back to the web page
6. The response is read by JavaScript
7. Proper action (like page update) is performed by JavaScript

AJAX - The XMLHttpRequest Object


The XMLHttpRequest Object
All modern browsers support the XMLHttpRequest object.

The XMLHttpRequest object can be used to exchange data with a server behind the scenes. This means
that it is possible to update parts of a web page, without reloading the whole page.

Create an XMLHttpRequest Object


All modern browsers (Chrome, Firefox, Edge (and IE7+), Safari, Opera) have a built-in
XMLHttpRequest object.

Syntax for creating an XMLHttpRequest object:

variable = new XMLHttpRequest();

Example
var xhttp = new XMLHttpRequest();

XMLHttpRequest Object Methods

Method Description

new XMLHttpRequest() Creates a new XMLHttpRequest object

abort() Cancels the current request

getAllResponseHeaders() Returns header information

getResponseHeader() Returns specific header information

open(method,url,async,user,psw) Specifies the request

method: the request type GET or POST


url: the file location
async: true (asynchronous) or false (synchronous)
user: optional user name
psw: optional password

send() Sends the request to the server


Used for GET requests

20
send(string) Sends the request to the server.
Used for POST requests

setRequestHeader() Adds a label/value pair to the header to be sent


XMLHttpRequest Object Properties

Property Description

onreadystatechange Defines a function to be called when the readyState property changes

readyState Holds the status of the XMLHttpRequest.


0: request not initialized
1: server connection established
2: request received
3: processing request
4: request finished and response is ready

responseText Returns the response data as a string

responseXML Returns the response data as XML data

status Returns the status-number of a request


200: "OK"
403: "Forbidden"
404: "Not Found"
For a complete list go to the Http Messages Reference

statusText Returns the status-text (e.g. "OK" or "Not Found


AJAX - Send a Request To a Server
The XMLHttpRequest object is used to exchange data with a server.

Send a Request To a Server


To send a request to a server, we use the open() and send() methods of the XMLHttpRequest object:

xhttp.open("GET", "ajax_info.txt", true);


xhttp.send();

GET or POST?
GET is simpler and faster than POST, and can be used in most cases.

However, always use POST requests when:

 A cached file is not an option (update a file or database on the server).


 Sending a large amount of data to the server (POST has no size limitations).

21
 Sending user input (which can contain unknown characters), POST is more robust and secure
than GET.

GET Requests
A simple GET request:

Example
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();

In the example above, you may get a cached result. To avoid this, add a unique ID to the URL:

POST Requests
A simple POST request:

Example
xhttp.open("POST", "demo_post.asp", true);
xhttp.send();

To POST data like an HTML form, add an HTTP header with setRequestHeader(). Specify the data you
want to send in the send() method:

Example
xhttp.open("POST", "demo_post2.asp", true);
xhttp.setRequestHeader("Content-type", "application/x-www-form-urlencoded");
xhttp.send("fname=Henry&lname=Ford");

The url - A File On a Server


The url parameter of the open() method, is an address to a file on a server:

xhttp.open("GET", "ajax_test.asp", true);

The file can be any kind of file, like .txt and .xml, or server scripting files like .asp and .php (which can
perform actions on the server before sending the response back).

Asynchronous - True or False?


 Server requests should be sent asynchronously.
 The async parameter of the open() method should be set to true:
 xhttp.open("GET", "ajax_test.asp", true);
By sending asynchronously, the JavaScript does not have to wait for the server response, but can instead:

 execute other scripts while waiting for server response


 deal with the response after the response is ready

The onreadystatechange Property


With the XMLHttpRequest object you can define a function to be executed when the request receives an
answer.

22
The function is defined in the onreadystatechange property of the XMLHttpResponse object:

Example
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML = this.responseText;
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:

<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

Synchronous Request
To execute a synchronous request, change the third parameter in the open() method to false:

xhttp.open("GET", "ajax_info.txt", false);

Sometimes async = false are used for quick testing. You will also find synchronous requests in older
JavaScript code.

Since the code will wait for server completion, there is no need for an onreadystatechange function:

AJAX - Server Response


The onreadystatechange Property
The readyState property holds the status of the XMLHttpRequest.

The onreadystatechange property defines a function to be executed when the readyState changes.

The status property and the statusText property holds the status of the XMLHttpRequest object.

The onreadystatechange function is called every time the readyState changes.

When readyState is 4 and status is 200, the response is ready:

Example
function loadDoc() {
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.responseText;
}
23
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();
}

The "ajax_info.txt" file used in the example above, is a simple text file and looks like this:

<h1>AJAX</h1>
<p>AJAX is not a programming language.</p>
<p>AJAX is a technique for accessing web servers from a web page.</p>
<p>AJAX stands for Asynchronous JavaScript And XML.</p>

The onreadystatechange event is triggered four times (1-4), one time for each change in the readyState.

Server Response Properties


Property Description

responseText get the response data as a string

responseXML get the response data as XML data

Server Response Methods


Method Description

getResponseHeader() Returns specific header information from the server resource

getAllResponseHeaders() Returns all the header information from the server resource
The responseText Property
The responseText property returns the server response as a JavaScript string, and you can use it
accordingly:

Example
document.getElementById("demo").innerHTML = xhttp.responseText;

The responseXML Property


The XML HttpRequest object has an in-built XML parser.

The responseXML property returns the server response as an XML DOM object.

Using this property you can parse the response as an XML DOM object:

Example
Request the file cd_catalog.xml and parse the response:

xmlDoc = xhttp.responseXML;
txt = "";
x = xmlDoc.getElementsByTagName("ARTIST");

24
for (i = 0; i < x.length; i++) {
txt += x[i].childNodes[0].nodeValue + "<br>";
}
document.getElementById("demo").innerHTML = txt;
xhttp.open("GET", "cd_catalog.xml", true);
xhttp.send();

The getAllResponseHeaders() Method


The getAllResponseHeaders() method returns all header information from the server response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getAllResponseHeaders();
}
};

The getResponseHeader() Method


The getResponseHeader() method returns specific header information from the server response.

Example
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
if (this.readyState == 4 && this.status == 200) {
document.getElementById("demo").innerHTML =
this.getResponseHeader("Last-Modified");
}
};
xhttp.open("GET", "ajax_info.txt", true);
xhttp.send();

jQuery Framework

What is jQuery?
 jQuery is a JavaScript framework. It facilitates the readability and the manipulation of HTML
DOM elements, event handling, animations, and AJAX calls. It’s also free, open-source
software that adheres to the MIT License. As a result, it is one of the most popular JavaScript
libraries.
 The syntax of jQuery makes document navigation, DOM component selection, animation
creation, event handling, and Ajax app development easier.
 It allows developers to create plug-ins that operate on top of the JavaScript library.
Developers may use this to construct abstractions for low-level interaction and animation,
complex effects, and themeable widgets at a high level.
 The modular nature of the jQuery framework allows developers to create complex dynamic
web pages and apps.

25
What is jQuery used for?
 jQuery is an open-source JavaScript library. So when we need to write less and get more
done, it’s light and convenient.
 jQuery is a library that covers several common activities that require a lot of JavaScript code
in different methods. Programmers may use a single line of code to invoke this function. As a
consequence, including JavaScript in your website is straightforward. JavaScript is an
independent programming language, whereas jQuery is a collection of JavaScript code (not
its own language).
 JQuery is a compact, quick JavaScript library packaged in a single.js file. It has several built-
in functionalities that allow you to complete various activities fast and efficiently.

Why use it?


 jQuery is a cross-browser library that is small, fast, and packed with features. As a result, it is
the most popular and widely used JavaScript framework among programmers, despite the
fact that there are numerous JavaScript libraries available. Moreover, it is more flexible and
straightforward to use than other JavaScript libraries.
 jQuery requires significantly less code, offers a wide variety of online plug-ins, and is easy to
use for web developers. It increases web pages’ interactivity, simplicity, and usability in all
browsers. It may also be optimised for SEO and is simple to set up and utilise.

jQuery Get Started


Adding jQuery to Your Web Pages

There are several ways to start using jQuery on your web site. You can:

 Download the jQuery library from jQuery.com


 Include jQuery from a CDN, like Google

Downloading jQuery

There are two versions of jQuery available for downloading:

 Production version - this is for your live website because it has been minified and compressed
 Development version - this is for testing and development (uncompressed and readable code)

Both versions can be downloaded from jQuery.com.

The jQuery library is a single JavaScript file, and you reference it with the HTML <script> tag (notice
that the <script> tag should be inside the <head> section):

<head>
<script src="jquery-3.7.1.min.js"></script>
</head>

Tip: Place the downloaded file in the same directory as the pages where you wish to use it.

jQuery CDN

If you don't want to download and host jQuery yourself, you can include it from a CDN (Content
Delivery Network).
26
Google is an example of someone who host jQuery:

Google CDN:
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
</head>

jQuery Syntax

With jQuery you select (query) HTML elements and perform "actions" on them.

jQuery Syntax

The jQuery syntax is tailor-made for selecting HTML elements and performing some action on the
element(s).

Basic syntax is: $(selector).action()

 A $ sign to define/access jQuery


 A (selector) to "query (or find)" HTML elements
 A jQuery action() to be performed on the element(s)

Examples:

$(this).hide() - hides the current element.

$("p").hide() - hides all <p> elements.

$(".test").hide() - hides all elements with class="test".

$("#test").hide() - hides the element with id="test".

Are you familiar with CSS selectors?

jQuery uses CSS syntax to select elements. You will learn more about the selector syntax in the next
chapter of this tutorial.

Tip: If you don't know CSS, you can read our CSS Tutorial.

The Document Ready Event

You might have noticed that all jQuery methods in our examples, are inside a document ready event:

$(document).ready(function(){

// jQuery methods go here...

});

This is to prevent any jQuery code from running before the document is finished loading (is ready).

27
It is good practice to wait for the document to be fully loaded and ready before working with it. This also
allows you to have your JavaScript code before the body of your document, in the head section.

Here are some examples of actions that can fail if methods are run before the document is fully loaded:

 Trying to hide an element that is not created yet


 Trying to get the size of an image that is not loaded yet

Tip: The jQuery team has also created an even shorter method for the document ready event:

$(function(){

// jQuery methods go here...

});

jQuery Selectors
 jQuery selectors are one of the most important parts of the jQuery library.
 jQuery selectors allow you to select and manipulate HTML element(s).
 jQuery selectors are used to "find" (or select) HTML elements based on their name, id, classes,
types, attributes, values of attributes and much more. It's based on the existing CSS Selectors, and
in addition, it has some own custom selectors.
 All selectors in jQuery start with the dollar sign and parentheses: $().
The element Selector

The jQuery element selector selects elements based on the element name.

You can select all <p> elements on a page like this:

$("p")

Example

When a user clicks on a button, all <p> elements will be hidden:

Example
$(document).ready(function(){
$("button").click(function(){
$("p").hide();
});
});

The #id Selector

The jQuery #id selector uses the id attribute of an HTML tag to find the specific element.

An id should be unique within a page, so you should use the #id selector when you want to find a single,
unique element.

28
To find an element with a specific id, write a hash character, followed by the id of the HTML element:

$("#test")

Example

When a user clicks on a button, the element with id="test" will be hidden:

Example
$(document).ready(function(){
$("button").click(function(){
$("#test").hide();
});
});

The .class Selector

The jQuery .class selector finds elements with a specific class.

To find elements with a specific class, write a period character, followed by the name of the class:

$(".test")

Example

When a user clicks on a button, the elements with class="test" will be hidden:

Example
<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("button").click(function(){
$(".test").hide();
});
});
</script>
</head>
<body>

<h2 class="test">This is a heading</h2>

<p class="test">This is a paragraph.</p>


<p>This is another paragraph.</p>

<button>Click me</button>

</body>
</html>
29
More Examples of jQuery Selectors
Syntax Description

$("*") Selects all elements

$(this) Selects the current HTML element

$("p.intro") Selects all <p> elements with class="intro"

$("p:first") Selects the first <p> element

$("ul li:first") Selects the first <li> element of the first <ul>

$("ul li:first-child") Selects the first <li> element of every <ul>

$("[href]") Selects all elements with an href attribute

$("a[target='_blank']") Selects all <a> elements with a target attribute value equal
to "_blank"

$("a[target!='_blank']") Selects all <a> elements with a target attribute value NOT
equal to "_blank"

$(":button") Selects all <button> elements and <input> elements of


type="button"

$("tr:even") Selects all even <tr> elements

$("tr:odd") Selects all odd <tr> elements

Use our jQuery Selector Tester to demonstrate the different selectors.

For a complete reference of all the jQuery selectors, please go to our jQuery Selectors Reference.

Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you
can put your jQuery functions in a separate .js file.

When we demonstrate jQuery in this tutorial, the functions are added directly into the <head> section.
However, sometimes it is preferable to place them in a separate file, like this (use the src attribute to refer
to the .js file):

Example
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>

30
Functions In a Separate File

If your website contains a lot of pages, and you want your jQuery functions to be easy to maintain, you
can put your jQuery functions in a separate .js file.

When we demonstrate jQuery in this tutorial, the functions are added directly into the <head> section.
However, sometimes it is preferable to place them in a separate file, like this (use the src attribute to refer
to the .js file):

Example
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script src="my_jquery_functions.js"></script>
</head>

jQuery Events

What are Events?


All the different visitors' actions that a web page can respond to are called events.
An event represents the precise moment when something happens.
Examples:
 moving a mouse over an element
 selecting a radio button
 clicking on an element
The term "fires/fired" is often used with events. Example: "The keypress event is fired, the moment you
press a key".

Here are some common DOM events:

Mouse Events Keyboard Events Form Events Document/Window Events

click keypress submit load

dblclick keydown change resize

mouseenter keyup focus scroll

mouseleave blur unload

jQuery Syntax For Event Methods


In jQuery, most DOM events have an equivalent jQuery method.
To assign a click event to all paragraphs on a page, you can do this:
$("p").click();
The next step is to define what should happen when the event fires. You must pass a function to the
event:

$("p").click(function(){
// action goes here!!
});

31
Commonly Used jQuery Event Methods

$(document).ready()
The $(document).ready() method allows us to execute a function when the document is fully loaded..

click()
The click() method attaches an event handler function to an HTML element.
The function is executed when the user clicks on the HTML element.
The following example says: When a click event fires on a <p> element; hide the current <p> element:
Example
$("p").click(function(){
$(this).hide();
});

dblclick()
The dblclick() method attaches an event handler function to an HTML element.
The function is executed when the user double-clicks on the HTML element:
Example

<!DOCTYPE html>
<html>
<head>
<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.7.1/jquery.min.js"></script>
<script>
$(document).ready(function(){
$("p").dblclick(function(){
$(this).hide();
});
});
</script>
</head>
<body>
<p>If you double-click on me, I will disappear.</p>
<p>Click me away!</p>
<p>Click me too!</p>
</body>

</html>

mouseenter()
The mouseenter() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer enters the HTML element:
Example
$("#p1").mouseenter(function(){
alert("You entered p1!");
});

mouseleave()
The mouseleave() method attaches an event handler function to an HTML element.
The function is executed when the mouse pointer leaves the HTML element:
Example

32
$("#p1").mouseleave(function(){
alert("Bye! You now leave p1!");
});

mousedown()
The mousedown() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is pressed down, while the mouse is
over the HTML element:
Example
$("#p1").mousedown(function(){
alert("Mouse down over p1!");
});

mouseup()
The mouseup() method attaches an event handler function to an HTML element.
The function is executed, when the left, middle or right mouse button is released, while the mouse is over
the HTML element:
Example
$("#p1").mouseup(function(){
alert("Mouse up over p1!");
});

hover()
The hover() method takes two functions and is a combination of the mouseenter() and mouseleave() methods.
The first function is executed when the mouse enters the HTML element, and the second function is
executed when the mouse leaves the HTML element:
Example
$("#p1").hover(function(){
alert("You entered p1!");
},
function(){
alert("Bye! You now leave p1!");
});

focus()
The focus() method attaches an event handler function to an HTML form field.
The function is executed when the form field gets focus:
Example
$("input").focus(function(){
$(this).css("background-color", "#cccccc");
});

blur()
The blur() method attaches an event handler function to an HTML form field.
The function is executed when the form field loses focus:
Example
$("input").blur(function(){
$(this).css("background-color", "#ffffff");
});

33
The on() Method
The on() method attaches one or more event handlers for the selected elements.
Attach a click event to a <p> element:
Example
$("p").on("click", function(){
$(this).hide();
});
Attach multiple event handlers to a <p> element:
Example
$("p").on({
mouseenter: function(){
$(this).css("background-color", "lightgray");
},
mouseleave: function(){
$(this).css("background-color", "lightblue");
},
click: function(){
$(this).css("background-color", "yellow");
}
});

UI components

What are UI components?


UI components are the most integral parts of a web application. They consist of all the app’s styles
and components, such as buttons, input fields, icons, and text. Essentially, they are the core building
blocks for all applications.

UI components are responsible for interactions between the user and the application. They facilitate
an effective user experience, and they allow the users to navigate through the application easily. UI
components also help them to efficiently perform various functions, like adding/editing information,
filtering data, and selecting a date on the calendar.

Why should you use UI components?

 Quickly create the user interface of your web application


 Reduce code duplication by using reusable components
 Save development time and money
 Easily update the UI when required

How can I easily create UI components for my JavaScript application?

You can easily create UI components for your JavaScript web application using Sencha Ext JS. It is
the most comprehensive framework for building data-intensive apps for all modern devices.

34
The UI of Ext JS applications is made up of widgets. They are known as components, and they are
subclasses of the Ext.Component class. You can easily extend them to create a customized
component for your web application.

How can I quickly build a login form?


Sencha Ext JS includes the form panel, a basic UI component with form handling capabilities. You
can use it whenever you need to collect data from the user. Using it, you can quickly build a login
form. Here is an example:

This is a simple login form that accepts the user ID and password. To create it, you have to follow
these simple steps:

1. First, you have to define a new custom class, called KitchenSink.view.form.LoginForm. Then
you have to extend Ext.form.Panel. You also need to define the type of UI component, which
is form-login.
Ext.define('KitchenSink.view.form.LoginForm', {
extend: 'Ext.form.Panel',
xtype: 'form-login',
2. Next, you have to specify title, frame, width, bodyPadding, and defaultType fields.
title: 'Login',
frame:true,
width: 320,
bodyPadding: 10,

defaultType: 'textfield',
3. Then you have to specify the items for “user ID”, “password”, and “Remember me” fields of the
form.

items: [{
allowBlank: false,
fieldLabel: 'User ID',
35
name: 'user',
emptyText: 'user id'
}, {
allowBlank: false,
fieldLabel: 'Password',
name: 'pass',
emptyText: 'password',
inputType: 'password'
}, {
xtype:'checkbox',
fieldLabel: 'Remember me',
name: 'remember'
}],
4. Now, you have to specify the Register and Login buttons.

buttons: [
{ text:'Register' },
{ text:'Login' }
],
5. Finally, you have to specify the defaults.

defaults: {
anchor: '100%',
labelWidth: 120
}
});

JSON Data Formats


What is JSON?

 JSON stands for JavaScript Object Notation


 JSON is a lightweight data-interchange format
 JSON is plain text written in JavaScript object notation
 JSON is used to send data between computers
 JSON is language independent *

*
The JSON syntax is derived from JavaScript object notation, but the JSON format is text only.

Code for reading and generating JSON exists in many programming languages.

The JSON format was originally specified by Douglas Crockford.

Why Use JSON?


 The JSON format is syntactically similar to the code for creating JavaScript objects. Because of
this, a JavaScript program can easily convert JSON data into JavaScript objects.
 Since the format is text only, JSON data can easily be sent between computers, and used by any
programming language.
 JavaScript has a built in function for converting JSON strings into JavaScript objects:
JSON.parse()
36
 JavaScript also has a built in function for converting an object into a JSON string:
JSON.stringify()

You can receive pure text from a server and use it as a JavaScript object.

You can send a JavaScript object to a server in pure text format.

You can work with data as JavaScript objects, with no complicated parsing and translations.

Storing Data

When storing data, the data has to be a certain format, and regardless of where you choose to store
it, text is always one of the legal formats.

JSON makes it possible to store JavaScript objects as text.

JSON Syntax

The JSON syntax is a subset of the JavaScript syntax.

JSON Syntax Rules

JSON syntax is derived from JavaScript object notation syntax:

 Data is in name/value pairs


 Data is separated by commas
 Curly braces hold objects
 Square brackets hold arrays

JSON Data - A Name and a Value

JSON data is written as name/value pairs (aka key/value pairs).

A name/value pair consists of a field name (in double quotes), followed by a colon, followed by a value:

Example
"name":"John"

JSON names require double quotes.

JSON - Evaluates to JavaScript Objects

The JSON format is almost identical to JavaScript objects.

In JSON, keys must be strings, written with double quotes:

JSON
{"name":"John"}

In JavaScript, keys can be strings, numbers, or identifier names:

37
JavaScript
{name:"John"}

JSON Data Types


Valid Data Types

In JSON, values must be one of the following data types:

 a string
 a number
 an object (JSON object)
 an array
 a boolean
 null

JSON values cannot be one of the following data types:

 a function
 a date
 undefined

JSON Strings

Strings in JSON must be written in double quotes.

Example
{"name":"John"}

JSON Numbers

Numbers in JSON must be an integer or a floating point.

Example
{"age":30}

JavaScript Objects

Because JSON syntax is derived from JavaScript object notation, very little extra software is needed to
work with JSON within JavaScript.

With JavaScript you can create an object and assign data to it, like this:

Example
person = {name:"John", age:31, city:"New York"};

You can access a JavaScript object like this:

Example
38
// returns John
person.name;

Example
// returns John
person["name"];

Data can be modified like this:

Example
person.name = "Gilbert";

It can also be modified like this:

Example
person["name"] = "Gilbert";

Accessing Object Values


<!DOCTYPE html>
<html>
<body>
<h2>Access a JavaScript Object</h2>
<p id="demo"></p>
<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);
document.getElementById("demo").innerHTML = myObj.name;
</script>
</body>
</html>
Looping an Object
You can loop through object properties with a for-in loop:
<!DOCTYPE html>
<html>
<body>

<h2>Looping Object Properties</h2>


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

<script>
const myJSON = '{"name":"John", "age":30, "car":null}';
const myObj = JSON.parse(myJSON);

let text = "";


for (const x in myObj) {
text += x + ", ";
}
document.getElementById("demo").innerHTML = text;
39
</script>

</body>
</html>

JSON Arrays

Values in JSON can be arrays.

Example
{
"employees":["John", "Anna", "Peter"]
}

JSON Booleans

Values in JSON can be true/false.

Example
{"sale":true}

JSON null

Values in JSON can be null.

Example
{"middlename":null}

JSON Files

 The file type for JSON files is ".json"


 The MIME type for JSON text is "application/json"

JSON.parse()

A common use of JSON is to exchange data to/from a web server.

When receiving data from a web server, the data is always a string.

Parse the data with JSON.parse(), and the data becomes a JavaScript object.

Example - Parsing JSON

Imagine we received this text from a web server:

'{"name":"John", "age":30, "city":"New York"}'

Use the JavaScript function JSON.parse() to convert text into a JavaScript object:

40
const obj = JSON.parse('{"name":"John", "age":30, "city":"New York"}');

Array as JSON

When using the JSON.parse() on a JSON derived from an array, the method will return a JavaScript
array, instead of a JavaScript object.

Example

const text = '["Ford", "BMW", "Audi", "Fiat"]';


const myArr = JSON.parse(text);

JSON.stringify()

A common use of JSON is to exchange data to/from a web server.

When sending data to a web server, the data has to be a string.

Convert a JavaScript object into a string with JSON.stringify().

Stringify a JavaScript Object

Imagine we have this object in JavaScript:

const obj = {name: "John", age: 30, city: "New York"};

Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(obj);

The result will be a string following the JSON notation.

myJSON is now a string, and ready to be sent to a server:

Example
const obj = {name: "John", age: 30, city: "New York"};
const myJSON = JSON.stringify(obj);

Stringify a JavaScript Array

It is also possible to stringify JavaScript arrays:

Imagine we have this array in JavaScript:

const arr = ["John", "Peter", "Sally", "Jane"];

Use the JavaScript function JSON.stringify() to convert it into a string.

const myJSON = JSON.stringify(arr);

41

You might also like