Unit 4th Javascript PDF
Unit 4th Javascript PDF
CASET College
APPLIED COMPUTING II
(WEB DESIGNING)
UNIT- IV
Introduction to JavaScript Objects
A javaScript object is an entity having state and behavior (properties and method). For
example: car, pen, bike, chair, glass, keyboard, monitor etc.
JavaScript is template based not class based. Here, we don't create class to get the object. But,
we direct create objects.
1. By object literal
2. By creating instance of Object directly (using new keyword)
3. By using an object constructor (using new keyword)
object={property1:value1,property2:value2.....propertyN:valueN}
As you can see, property and value is separated by : (colon). Let’s see the simple
example of creating object in JavaScript.
<script>
emp={id:102,name:"paul",salary:40000}
</script>
Here, new keyword is used to create object. Let’s see the example of creating object
directly.
<script>
var emp=new Object();
emp.id=101;
emp.name="paul";
emp.salary=50000;
document.write(emp.id+" "+emp.name+" "+emp.salary);
</script>
<script>
function emp(id,name,salary){
this.id=id;
this.name=name;
this.salary=salary; }
e=new emp(103,"paul",30000);
document.write(e.id+" "+e.name+" "+e.salary);
</script>
In this tutorial, you will learn about JavaScript getter and setter methods
with the help of examples.
Data properties
Accessor properties
Data Property
Here's an example of data property that we have been using in the
previous tutorials.
const student = {
// data property
firstName: 'Monica';
};
Accessor Property
In JavaScript, accessor properties are methods that get or set the value of
an object. For that, we use these two keywords:
JavaScript Getter
const student = {
// data property
firstName: 'Monica',
// accessor property(getter)
get getName() {
return this.firstName;
}
};
get getName() {
return this.firstName;
}
And also when accessing the value, we access the value as a property.
student.getName;
console.log(student.getName()); // error
JavaScript Setter
In JavaScript, setter methods are used to change the values of an object.
For example,
const student = {
firstName: 'Monica',
//accessor property(setter)
set changeName(newName) {
this.firstName = newName;
}
};
console.log(student.firstName); // Monica
console.log(student.firstName); // Sarah
Run Code
In the above example, the setter method is used to change the value of an
object.
set changeName(newName) {
this.firstName = newName;
}
student.changeName = 'Sarah';
JavaScript Object.defineProperty()
In JavaScript, you can also use Object.defineProperty() method to add
getters and setters. For example,
const student = {
firstName: 'Monica'
}
// getting property
Object.defineProperty(student, "getName", {
get : function () {
return this.firstName;
}
});
// setting property
Object.defineProperty(student, "changeName", {
set : function (value) {
this.firstName = value;
}
});
console.log(student.firstName); // Monica
console.log(student.firstName); // Sarah
Run Code
Example
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
The delete operator deletes both the value of the property and the property
itself.
After deletion, the property cannot be used before it is added back again.
1. hasOwnProperty() method
Every JavaScript object has a special
method object.hasOwnProperty('myProp') that returns a boolean
indicating whether object has a property myProp.
The method name hasOwnProperty() suggests that it looks for the own
properties of the object. The own properties are those defined directly
upon the object.
2. in operator
'myProp' in object also determines whether myProp property exists
in object.
Now you can see the idea: you can compare with undefined to
determine the existence of the property.
const hero = {
name: 'Batman'
};
Even if the property name exists (but has undefined value), hero.name !==
undefined evaluates to false: which incorrectly indicates a missing
property.
Hina Gojwari
CASET College
4. Summary
There are mainly 3 ways to check if the properties or keys exist in an
object.
Finally, you can simply use object.propName !== undefined and compare
against undefined directly.
Serializing Objects
JavaScript Arrays
An array is a special variable, which can hold more than one value:
However, what if you want to loop through the cars and find a specific one?
And what if you had not 3 cars, but 300?
The solution is an array! An array can hold many values under a single
name, and you can access the values by referring to an index number.
Creating an Array
Using an array literal is the easiest way to create a JavaScript Array.
Syntax:
Learn more about const with arrays in the chapter: JS Array Const.
Example
const cars = ["Saab", "Volvo", "BMW"];
Spaces and line breaks are not important. A declaration can span multiple
lines:
const cars = [
"Saab",
"Volvo",
"BMW"
];
Hina Gojwari
CASET College
You can also create an array, and then provide the elements:
Example
const cars = [];
cars[0]= "Saab";
cars[1]= "Volvo";
cars[2]= "BMW";
Example
const cars = new Array("Saab", "Volvo", "BMW");
The two examples above do exactly the same. There is no need to use new
Array(). For simplicity, readability and execution speed, use the array literal
method.
cars[0] = "Opel";
Example :
const cars = ["Saab", "Volvo", "BMW"];
cars[0] = "Opel";
Hina Gojwari
CASET College
Array:
const person = ["John", "Doe", 46];
Object:
const person = {firstName:"John", lastName:"Doe", age:46};
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let length = fruits.length;
The length property is always one more than the highest array index.
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
let fLen = fruits.length;
Example
const fruits = ["Banana", "Orange", "Apple", "Mango"];
function myFunction(value) {
text += "<li>" + value + "</li>";
}
The second parameter is limit, the input should an integer that will limit the number
of splits.
Example 1
Following is the example of converting a string to an array using the split() method
−
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
</body>
</html>
O/p
We,are,CASET,College
W,e, ,a,r,e, ,C,A,S,E,T, ,C,o,l,l,e,g,e
We,are
WeareCASETCollege
Example 2
<!DOCTYPE html>
<html>
<title>Converting string to an array in JavaScript</title>
<head>
<script>
var string = "Oh, you are working CASET? that place is amazing! how can
i join there; is there any vacancy? please let me know.";
const array = string.split(/[.,!,?,;]/);
document.write(array);
</script>
</head>
<body>
</body>
</html>
O/p
Oh, you are working CASET, that place is amazing, how can i join there, is there
any vacancy, please let me know,
Example
Following is the example, where we used Array.from() method to convert string to an
array −
<!DOCTYPE html>
<html>
<head>
<script>
document.write(arr);
</script>
</head>
<body>
</body>
</html>
Hina Gojwari
CASET College
O/p
C,A,S,E,T
Example
Following is the example to convert string to an array −
<!DOCTYPE html>
<html>
<head>
<script>
document.write(arr);
</script>
</head>
<body>
</body>
</html>
<html>
<head>
<script>
document.write(arr);
</script>
</head>
<body>
</body>
</html>
O/p
H,i,n,a, ,i,s, ,a, ,c,u,l,t, ,c,l,a,s,s,i,c
Hina Gojwari
CASET College
With the object model, JavaScript gets all the power it needs to create
dynamic HTML:
JavaScript has a few window object methods that you can use to interact
with your users. The prompt() method lets you open a client-side window
and take input from a user. For instance, maybe you want the user to
enter a first and last name. Normally, you can use an HTML form for user
input, but you might need to get the information before sending the form
back to your server for processing. You can use the window.prompt()
method for small amounts of information. It's not meant for large blocks
of text, but it's useful when you need information before the user
continues to another page.
if (customerName!= null) {
document.getElementById("welcome").innerHTML =
The first line of code uses the prompt method. Notice that we don't need
the "window" object since JavaScript inherits the main DOM methods and
understands that this is an internal method. The first parameter in the
prompt is what you want to show the user. In this example, we want the
user to enter a name, so the prompt displays "Please enter your name."
The second parameter is the default text. This default text helps the user
understand where to type the name, but if he clicks "OK" without entering
a name, the "<name goes here>" text will be used for the username. You
can create checks in your JavaScript code that detects when the user
doesn't enter a name and just clicks OK, but this code assumes any text
entered is the user's name.
only checks that some character was entered, so the user can type
anything to bypass the "if" statement. The code within the "if" statement
then displays the message to the user in the "welcome" div. We've
covered reading and writing text to a web page, and this is another
example of writing text to the inner HTML section of a div. Remember
that the innerHTML property writes any tags or text within the opening
and closing div tag.
Use this method to get a short string response from your users before
they access a page or before they move on to another page in your site
structure.
The window.prompt method is one way to read user input, but JavaScript
also provides a way to get confirmation from the user. For instance, you
might want to confirm that the user has entered the right information and
wants to continue with payment. The confirmation window displays the
amount the user will be charged, and the user has the option to confirm
or cancel. You could write a complex JavaScript function to create a new
window for confirmation or you can use the internal window.confirm
method. This method returns either a boolean true result if the user clicks
"OK" or the boolean false result if the user clicks "Cancel." This prompt is
a quick way to get confirmation without using any complex coding logic.
if (r == true) {
x = "Payment sent!";
} else {
x = "Payment cancelled!";
}
Hina Gojwari
CASET College
alert (x);
The main utility in the above code is the "confirm" function. This is an
internal JavaScript function from the window object. In other words, using
"window.confirm()" and "confirm" results in the same function. JavaScript
handles the inheritance for you, so you don't need to remember to use
the window object. The confirmation window is also pre-built and shown
to the user. In this example, a prompt displays with the text "Are you
sure you want to send a payment?" The only options for the user are to
click the Cancel button or the OK button. OK is the confirmation that
returns "true." If the user clicks "OK," the variable x contains the text
"Payment sent!" Conversely, if the user clicks the "Cancel" button, x
contains the text "Payment cancelled!" The text is then displayed to the
user using the "alert" function. This is the first time we've seen the alert
function, which is also a part of the window object. Typing "alert" and
"window.alert" results in the same method call. The alert prompt is
common during debugging and development of a web application,
because it's a quick way to check your logic and see the control flow of
your code. The alert function in this example checks that the confirm
window is responding with the right result and the x variable contains the
right text.
There are three main HTML tags used to display text after you prompt
users. You've seen two internal JavaScript functions that get user input,
but how do you display it back to the user? The three tags used are the
div, span and text tags. The third one, the text tag, is a form field used to
take string input from the user. You usually use this tag to get input such
as a name or an address, but you can also display input from the user.
The span and div tags are a way to just display the information you've
read in JavaScript prompt windows. You can also display data you've
retrieved from a database.
Let's use the previous example where we prompted the user to enter a
name. We then use the input to display output in a div element. We've
Hina Gojwari
CASET College
seen this before, but this is the first time we've used input directly from
the user.
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
</body>
</html>
We've included the HTML this time to show you how JavaScript prompts
work with HTML elements. The element we're using is the div HTML tag
with the id of "welcome." The JavaScript prompt asks the user for his
name and then displays the result in the "welcome" div. You can also use
this same code to display the result in the span element using the same
code except change the div tag to a span opening and closing tag.
You've seen the innerHTML property several times, which controls the text
within the opening and closing div or span tags, but what if you want to
use the input to pre-populate a form field? The input text field lets users
input string values, but you can use the methods we've seen to pre-
populate string values automatically. Using the same input example as we
Hina Gojwari
CASET College
previously used, the following code uses the input prompt to enter the
user's name in the "username" text field.
<!DOCTYPE html>
<html>
<head>
<script>
</script>
</head>
<body>
Using innerHTML
To access an HTML element, JavaScript can use
the document.getElementById(id) method.
The id attribute defines the HTML element. The innerHTML property defines the
HTML content:
Hina Gojwari
CASET College
Example
<!DOCTYPE html>
<html>
<body>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
</body>
</html>
Using document.write()
For testing purposes, it is convenient to use document.write():
Example
<!DOCTYPE html>
<html>
<body>
<script>
document.write(5 + 6);
</script>
</body>
</html>
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Using window.alert()
You can use an alert box to display data:
Example
<!DOCTYPE html>
<html>
<body>
<script>
window.alert(5 + 6);
</script>
</body>
</html>
In JavaScript, the window object is the global scope object. This means that
variables, properties, and methods by default belong to the window object.
This also means that specifying the window keyword is optional:
Example
<!DOCTYPE html>
<html>
<body>
Hina Gojwari
CASET College
<script>
alert(5 + 6);
</script>
</body>
</html>
Using console.log()
For debugging purposes, you can call the console.log() method in the browser
to display data.
Example
<!DOCTYPE html>
<html>
<body>
<script>
console.log(5 + 6);
</script>
</body>
</html>
JavaScript Print
JavaScript does not have any print object or print methods.
The only exception is that you can call the window.print() method in the
browser to print the content of the current window.
Example
<!DOCTYPE html>
<html>
<body>
</body>
</html>
Hina Gojwari
CASET College
JavaScript Events
HTML events are "things" that happen to HTML elements.
HTML Events
An HTML event can be something the browser does, or something a user
does.
Example
<button onclick="document.getElementById('demo').innerHTML =
Date()">The time is?</button>
O/P
Hina Gojwari
CASET College
In the example above, the JavaScript code changes the content of the
element with id="demo".
In the next example, the code changes the content of its own element
(using this.innerHTML):
Example
<button onclick="this.innerHTML = Date()">The time is?</button>
O/P
Event Description
onmouseout The user moves the mouse away from an HTML element
Many different methods can be used to let JavaScript work with events:
“Web design is not just about creating pretty layouts. It's about
understanding the marketing challenge behind your business.”
ALL THE BEST !!