Unit 4 Comp Notes
Unit 4 Comp Notes
Web development is associated with a different kind of programming paradigm called web
programming. A person who programs a website is called a web programmer. It is the area
which is concerned with writing of source code (computer program) to create a website. Web
programming is sometimes called scripting. The source code is written in some scripting
language. Web applications require multi-platform accessibility and employ a hypermedia
paradigm. It may be static or dynamic depending upon the requirement of an organization.
A dynamic website is more complex where contents of website are changed frequently. It is
written in HTML and some scripting language which dynamically updates the contents being
requested by the user.
Introduction to Client-side Scripting:
Client-side
• Server-side
This module is about client-side scripting. Client-side scripts execute within a user's browser and are used
to manage forms and form fields. Examples of things client-side scripts can do include:
• Loaded
• Changed
• Submitted
a) onLoad
onLoad Client Scripts execute script logic when forms are loaded. Uses onload Client Scripts
to manipulate a form's appearance or content. For example, setting field or form-level messages
based on the presence of a value. Uses onLoad Client Scripts sparingly as theyimpact form load
times.
b) onChange:
onChange Client Scripts execute script logic when a particular field's value changes. Use
onChange Client Scripts to respond to field values of interest and to modify anotherfield's
value or attributes. For example, if the State field's value changes to Closed Complete, generate
an alert and make the Description field mandatory.
c) onSubmit:
onSubmit Client Scripts execute script logic when a form is submitted. Use onSubmit Client
Scripts to validate field values. For example, if a user submits a Priority 1 record, the script
can generate a confirmation dialog notifying the user that the executive staffs are copied on
all Priority 1 requests.
Introduction to Java Script:
What is JavaScript?
JavaScript is a very powerful client-side scripting language. JavaScript is used mainly for
enhancing the interaction of a user with the webpage. In other words, you can make your webpage
livelier and more interactive, with the help of JavaScript. JavaScript is also being used widely in
game development and Mobile application development.
When JavaScript was created, it initially had another name: “LiveScript”. But Java was very popular at that time,
so it was decided that positioning a new language as a “younger brother” of Java would help. But as it evolved,
JavaScript became a fully independent language with its own specification called ECMAScript, and now it has
no relation to Java at all.
Today, JavaScript can execute not only in the browser, but also on the server, or actually on any device that has
a special program called the JavaScript engine. The browser has an embedded engine sometimes called a
“JavaScript virtual machine”.
Different engines have different “codenames”. For example:
The terms above are good to remember because they are used in developer articles on the internet. We’ll use them
too. For instance, if “a feature X is supported by V8”, then it probably works in Chrome and Opera.
The engine applies optimizations at each step of the process. It even watches the compiled script as it runs,
analyzes the data that flows through it, and further optimizes the machine code based on that knowledge.
JavaScript History:
JavaScript was developed by Brendan Eich in 1995, which appeared in Netscape, a popular
browser of that time.
Tools You Need
To start with, you need a text editor to write your code and a browser to display the web pages
you develop.
You can use a text editor of your choice including Notepad++, Visual Studio Code,
Sublime Text, Atom or any other text editor you are comfortable with.
You can use any web browser including Google Chrome, Firefox, Microsoft Edge,
Internet Explorer etc.
<script type="text/javascript">
<html>
<head>
<title>My First JavaScript code!!!</title>
<script>
alert ("Hello World!");
</script>
</head>
<body>
</body>
</html>
What makes JavaScript unique?
There are at least three great things about JavaScript:
Full integration with HTML/CSS.
Simple things are done simply.
Support by all major browsers and enabled by default.
JavaScript is the only browser technology that combines these three things.
That’s what makes JavaScript unique. That’s why it’s the most widespread tool for creating
browser interfaces. That said; JavaScript also allows creating servers, mobile applications, etc.
The example below "finds" an HTML element (with id="demo"), and changes the element
content (innerHTML) to "Hello JavaScript":
Example
Example
Example
[Link]("demo").[Link] = "35px";
Example
[Link]("demo").[Link] = "none";
Example
[Link]("demo").[Link] = "block";
Features of JavaScript:
According to a recent survey conducted by Stack Overflow, JavaScript is the most popular
language on earth. With advances in browser technology and JavaScript having moved into the
server with [Link] and other frameworks, JavaScript is capable of so much more. Here are a few
things that we can do with JavaScript:
• JavaScript was created in the first place for DOM manipulation. Earlier websites were
mostly static, after JS was created dynamic Web sites were made.
• Functions in JS are objects. They may have properties and methods just like another
object. They can be passed as arguments in other functions.
• Can handle date and time.
• Performs Form Validation although the forms are created using HTML.
• No compiler needed.
OR
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 astructured
programming language.
3. JavaScript is a weakly typed language, where certain types are implicitly cast (depending on the
operation).
4. JavaScript is an object-oriented programming language that uses prototypes rather thanusing 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.
Application of JavaScript
JavaScript is used to create interactive websites. It is mainly used for:
o Client-side validation,
o Dynamic drop-down menus,
o Displaying date and time,
o Displaying pop-up windows and dialog boxes (like an alert dialog box, confirm dialog box
and prompt dialog box),
o Displaying clocks etc.
Platform for JavaScript:
• Web Development: Adding interactivity and behavior to static sites JavaScript was
invented to do this in 1995. By using AngularJS that can be achieved so easily.
• Web Applications: With technology, browsers have improved to the extent that a language
was required to create robust web applications. When we explore a map in Google Maps
then we only need to click and drag the mouse. All detailed view is just a click away, and
this is possible only because of JavaScript. It uses Application Programming Interfaces
(APIs) that provide extra power to the code. The Electron and React is helpful in this
department.
• Server Applications: With the help of [Link], JavaScript made its way from client to
server and [Link] is the most powerful in the server-side.
• Games: Not only in websites, JavaScript also helps in creating games for leisure. The
combination of JavaScript and HTML 5 makes JavaScript popular in game development
as well. It provides the Ease JS library which provides solutions for working with rich
graphics.
• Smart watches: JavaScript is being used in all possible devices and applications. Itprovides
a library Pebble JS which is used in smart watch applications. This framework works for
applications that require the internet for its functioning.
• Art: Artists and designers can create whatever they want using JavaScript to draw on HTML
5 canvas, make sound more effective also can be used [Link] library.
• Machine Learning: This JavaScript [Link] library can be used in web development by
using machine learning.
JavaScript is a dynamic type language; means you don't need to specify type of the variable because it is
dynamically used by JavaScript engine. You need to use var here to specify the data type. It can hold any type
of values such as numbers, strings etc. For example:
JavaScript variables can hold many data types: numbers, strings, objects and more:
var x = 16 + "Volvo";
Does it make any sense to add "Volvo" to sixteen? Will it produce an error or will it produce a result?
When adding a number and a string, JavaScript will treat the number as astring.
Example:
var x = 16 + "Volvo";
Example
var x; // Now x is undefined
x = 5; // Now x is a Number
x = "John"; // Now x is a String
JavaScript Strings
Strings are written with quotes. You can use single or double quotes:
Example
var carName1 = "Volvo XC60"; // Using double quotes
var carName2 = 'Volvo XC60'; // Using single quotes
You can use quotes inside a string, as long as they don't match the quotes
surrounding the string:
Example
var answer1 = "It's alright"; // Single quote inside double
quotes
var answer2 = "He is called 'Johnny'"; // Single quotes inside double
quotes
var answer3 = 'He is called "Johnny"'; // Double quotes inside single
quotes
JavaScript Numbers:
JavaScript has only one type of numbers.
Extra large or extra small numbers can be written with scientific (exponential) notation:
Example
var y = 123e5; // 12300000
var z = 123e-5; // 0.00123
JavaScript Booleans:
Booleans can only have two values: true or false.
Example
var x = 5;
var y = 5;
var z = 6;
(x == y) // Returns true
(x == z) // Returns false
JavaScript Arrays:
JavaScript arrays are written with square brackets.
The following code declares (creates) an array called cars, containing three items (car
names):
Example
var cars = ["Saab", "Volvo", "BMW"];
Array indexes are zero-based, which means the first item is [0], second is [1], and so
on.
JavaScript Objects:
JavaScript objects are written with curly braces {}.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
The object (person) in the example above has 4 properties: firstName, lastName, age,
and eyeColor.
Undefined:
In JavaScript, a variable without a value, has the value undefined. The type is
also undefined.
Example
var car; // Value is undefined, type is undefined
Example
car = undefined; // Value is undefined, type is undefined
Empty Values:
An empty value has nothing to do with undefined.
Example
var car = ""; // The value is "", the typeof is "string"
Null:
In JavaScript null is "nothing". It is supposed to be something that doesn't exist.
Unfortunately, in JavaScript, the data type of null is an object.
You can consider it a bug in JavaScript that typeof null is an object. It should
be null.
Example
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};
person = null; // Now value is null, but type is still an object
Variables in JavaScript:
➢ Local variable
➢ 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
<script>
var x = 10;
var y = 20;
var z=x+y;
[Link](z);
</script>
<script>
function abc(){
var x=10;//local variable
}
</script>
Or,
<script>
If(10<13){
var y=20;//JavaScript local variable
}
</script>
For example:
<script>
var data=200;//gloabal variable
function a(){
[Link](data);
}
function b(){
[Link](data);
}
a();//calling JavaScript function
b();
</script>
Operators in JS:
JavaScript operators are symbols that are used to perform operations on operands. For example:
var sum=10+20;
Example:
1. Arithmetic Operators
2. Comparison (Relational) Operators
3. Bitwise Operators
4. Logical Operators
5. Assignment Operators
6. Special Operators
var x = 10;
var x = 5;
var y = 2;
var z = x + y;
var x = 5;
var y = 2;
var z = x * y;
JavaScript Arithmetic Operators:
Operator Description
+ Addition
- Subtraction
* Multiplication
** Exponentiation (ES2016)
/ Division
++ Increment
-- Decrement
= x=y x=y
+= x += y x=x+y
-= x -= y x=x-y
*= x *= y x=x*y
/= x /= y x=x/y
%= x %= y x=x%y
**= x **= y x = x ** y
JavaScript String Operators:
John Doe
Adding two numbers will return the sum, but adding a number and a string
will return a string:
var x = 5 + 5;
var y = "5" + 5;
var z = "Hello" + 5;
10
55
Hello5
JavaScript Comparison Operators:
Operator Description
== equal to
!= not equal
? ternary operator
|| logical or
! logical not
JavaScript Type Operators:
Operator Description
The examples above uses 4 bits unsigned examples. But JavaScript uses 32-bit
signed numbers.
Because of this, in JavaScript, ~ 5 will not return 10. It will return -6.
~00000000000000000000000000000101 will return
11111111111111111111111111111010
Conditions Statements:
While writing a program, there may be a situation when you need to adopt one out of a given set of paths. In
such cases, you need to use conditional statements that allow your program to make correct decisions and
perform right actions.
JavaScript supports conditional statements which are used to perform different actions based on different
conditions. Here we will explain the if..else statement.
The following flow chart shows how the if-else statement works.
The if/else statement executes a block of code if a specified condition is true. If the condition is false, another
block of code can be executed. The if/else statement is a part of JavaScript's "Conditional" Statements, which
are used to perform different actions based on different conditions.
Syntax
• The if statement specifies a block of code to be executed if a condition is true:
• if (condition) {
// block of code to be executed if the condition is true
}
• The else statement specifies a block of code to be executed if the condition is false:
• if (condition) {
// block of code to be executed if the condition is true
} else {
// block of code to be executed if the condition is false
}
• The else if statement specifies a new condition if the first condition is false:
• if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and
condition2 is true
} else {
// block of code to be executed if the condition1 is false and
condition2 is false
}
Parameter Values
Parameter Description
if (condition)
{
lines of code to be executed if condition is true
}
JavaScript Loop:
Looping in programming languages is a feature which facilitates the execution of a set of instructions/functions
repeatedly while some condition evaluates to true. For example, suppose we want to print “Hello World” 10 times.
This can be done in two ways as shown below:
Iterative Method
In Loop, the statement needs to be written only once and the loop will be executed 10 times as shown below:
1. for loop
2. while loop
3. do-while loop
4. for-in loop
❖ for loop: for loop provides a concise way of writing the loop structure. Unlike a while
loop, a for statement consumes the initialization, condition and increment/decrement in one
line thereby providing a shorter, easy to debug structure of looping.
increment/decrement)
statement(s)
Flowchart:
1. Initialization condition: Here, we initialize the variable in use. It marks the start of a for loop. An
already declared variable can be used or a variable can be declared, local to loop only.
2. Testing Condition: It is used for testing the exit condition for a loop. It must return a boolean
value. It is also an Entry Control Loop as the condition is checked prior to the execution of the
loop statements.
3. Statement execution: Once the condition is evaluated to true, the statements in the loop body
are executed.
4. Increment/ Decrement: It is used for updating the variable for next iteration.
5. Loop termination: When the condition becomes false, the loop terminates marking the end of
its life cycle.
var x;
< /script>
Output:
Value of x:2
Value of x:3
Value of x:4
❖ while loop: A while loop is a control flow statement that allows code to be executed
repeatedly based on a given Boolean condition. The while loop can be thought of as a
repeating if statement.
Syntax :
while (boolean condition)
{
loop statements...
}
Flowchart:
• While loop starts with the checking of condition. If it evaluated to true, then the loop body
statements are executed otherwise first statement following the loop is executed. For this reason
it is also called Entry control loop
• Once the condition is evaluated to true, the statements in the loop body are executed. Normally
the statements contain an update value for the variable being processed for the next iteration.
• When the condition becomes false, the loop terminates which marks the end of its life cycle.
var x = 1;
❖ The JavaScript do while loop iterates the elements for the infinite number of times like
while loop. But, code is executed at least once whether condition is true or false. The syntax
of do while loop is given below.
❖ do while: do while loop is similar to while loop with only difference that it checks for
condition after executing the statements, and therefore is an example of Exit Control Loop.
Syntax:
do
{
statements..
}
while (condition);
1. do while loop starts with the execution of the statement(s). There is no checking of any
condition for the first time.
2. After the execution of the statements, and update of the variable value, the condition is checked
for true or false value. If it is evaluated to true, next iteration of loop starts.
3. When the condition becomes false, the loop terminates which marks the end of its life cycle.
4. It is important to note that the do-while loop will execute its statements at-least once before any
condition is checked, and therefore is an example of exit control loop.
var x = 21;
do
{
// The line while be printer even
// if the condition is false
[Link]("Value of x:" + x + "<br />");
x++;
} while (x < 20);
< /script>
Output:
Value of x: 21
JS Popup Boxes:
In JavaScript, popup boxes are used to display the message or notification to the user.
1. Alert Box
2. Confirm Box
3. Prompt Box.
1. Alert Box:
An alert dialog box is mostly used to give a warning message to the users. For example, if one input
field requires entering some text but the user does not provide any input, then as a part of validation,
you can use an alert box to give a warning message.
Nonetheless, an alert box can still be used for friendlier messages. Alert box gives only one button
"OK" to select and proceed.
Syntax:
[Link]("sometext");
<html>
<head>
<script type = "text/javascript">
<!--
function Warn() {
alert ("This is a warning message!");
[Link] ("This is a warning message!");
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick = "Warn();"
/>
</form>
</body>
</html>
Output:
This is a warning message!
2. Confirm Box:
A confirmation dialog box is mostly used to take user's consent on any option. It displays a dialog
box with two buttons: OK and Cancel.
If the user clicks on the OK button, the window method confirm () will return true. If the user clicks
on the Cancel button, then confirm () returns false. You can use a confirmation dialog box as
follows.
Syntax:
[Link]("sometext");
<html>
<head>
<script type = "text/javascript">
<!--
function getConfirmation() {
var retVal = confirm("Do you want to continue ?");
if( retVal == true ) {
[Link] ("User wants to continue!");
return true;
} else {
[Link] ("User does not want to continue!");
return false;
}
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick =
"getConfirmation();" />
</form>
</body>
</html>
Output:
User wants to continue!
3. Prompt Box:
The prompt dialog box is very useful when you want to pop-up a text box to get user input. Thus, it
enables you to interact with the user. The user needs to fill in the field and then click OK.
This dialog box is displayed using a method called prompt() which takes two parameters:
(i) a label which you want to display in the text box and
(ii) a default string to display in the text box.
This dialog box has two buttons: OK and Cancel. If the user clicks the OK button, the window method
prompt() will return the entered value from the text box. If the user clicks the Cancel button, the window
method prompt() returns null.
Syntax:
[Link]("sometext","defaultText");
<html>
<head>
<script type = "text/javascript">
<!--
function getValue() {
var retVal = prompt("Enter your name : ", "your name
here");
[Link]("You have entered : " + retVal);
}
//-->
</script>
</head>
<body>
<p>Click the following button to see the result: </p>
<form>
<input type = "button" value = "Click Me" onclick =
"getValue();" />
</form>
</body>
</html>
Output:
You have entered: your name here
JS Events:
What is an Event?
JavaScript's interaction with HTML is handled through events that occur when the user or the browser
manipulates a page.
When the page loads, it is called an event. When the user clicks a button, that click too is an event. Other
examples include events like pressing any key, closing a window, resizing a window, etc.
Developers can use these events to execute JavaScript coded responses, which cause buttons to close
windows, messages to be displayed to users, data to be validated, and virtually any other type of response
imaginable.
Events are a part of the Document Object Model (DOM) Level 3 and every HTML element contains a set
of events which can trigger JavaScript Code.
JavaScript Events:
The change in the state of an object is known as an Event. In html, there are various events which
represents that some activity is performed by the user or by the browser. When
javascript code is included in HTML, js react over these events and allow the execution. This
process of reacting over the events is called Event Handling. Thus, js handles the HTML events
via Event Handlers.
For example, when a user clicks over the browser, add js code, which will execute the task to be
performed on the event.
HTML Events:
An HTML event can be something the browser does, or something a user does.
HTML allows event handler attributes, with JavaScript code, to be added to HTML elements.
mouseover onmouseover When the cursor of the mouse comes over the element
mousedown onmousedown When the mouse button is pressed over the element
mouseup onmouseup When the mouse button is released over the element
➢ Keyboard events:
Keydown & Keyup onkeydown & onkeyup When the user press and then release the key
➢ Form events:
change onchange When the user modifies or changes the value of a form element
➢ Window/Document events
load onload When the browser finishes the loading of the page
unload onunload When the visitor leaves the current webpage, the
browser unloads it
resize onresize When the visitor resizes the window of the browser
Click Event:
<html>
<head> Javascript Events </head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function clickevent()
{
[Link]("This is JavaTpoint");
}
//-->
</script>
<form>
<input type="button" onclick="clickevent()" value="Who's this?"/>
</form>
</body>
</html>
Mouse over Event:
<html>
<head>
<h1> Javascript Events </h1>
</head>
<body>
<script language="Javascript" type="text/Javascript">
<!--
function mouseoverevent()
{
alert("This is JavaTpoint");
}
//-->
</script>
<p onmouseover="mouseoverevent()"> Keep cursor over me</p>
</body>
</html>
Focus Event:
<html>
head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onfocus="focusevent()"/>
<script>
<!--
function focusevent()
{
[Link]("input1").[Link]=" aqua";
}
//-->
</script>
</body>
</html>
Key-down Event
<html>
<head> Javascript Events</head>
<body>
<h2> Enter something here</h2>
<input type="text" id="input1" onkeydown="keydownevent()"/>
<script>
<!--
function keydownevent()
{
[Link]("input1");
alert("Pressed a key");
}
//-->
</script>
</body>
</html>
Load event:
<html>
<head>Javascript Events</head>
</br>
<body onload="[Link]('Page successfully loaded');">
<script>
<!--
[Link]("The page is loaded successfully");
//-->
</script>
</body>
</html>
JS Arrays, Working with Arrays:
Arrays in JavaScript:
In JavaScript, array is a single variable that is used to store different elements. It isoften used when we want
to store list of elements and access them by a single variable. Unlike most languages where array is a
reference to the multiple variables,in JavaScript array is a single variable that stores multiple elements.
What is an Array?
An array is a special variable, which can hold more than one value at a time.
If you have a list of items (a list of car names, for example), storing the cars in single
variables could look like this:
An array can hold many values under a single name, and you can access the values by
referring to an index number.
1. By array literal
2. By creating instance of Array directly (using new keyword)
3. By using an Array constructor (using new keyword)
Creating an Array:
Syntax:
Example:
Spaces and line breaks are not important. A declaration can span multiple lines:
Example:
var cars = [
"Saab",
"Volvo",
"BMW"
];
The following example also creates an Array, and assigns values to it:
Example:
The two examples above do exactly the same. There is no need to use new
Array().
For simplicity, readability and execution speed, use the first one (the array
literal method).
1. Access the Full Array:
With JavaScript, the full array can be accessed by referring to the array name:
Example:
Arrays use numbers to access its "elements". In this example, person[0] returns John:
Array:
Objects use names to access its "members". In this example, [Link] returns
John:
Object:
var person = {firstName:"John" lastName:"Doe" age:46};
Examples:
var x = [Link]; // The length property returns the number of elements
var y = [Link](); // The sort() method sorts arrays
The length Property:
The length property of an array returns the length of an array (the number of array
elements).
Example:
JS Objects :
A JavaScript object is an entity having state and behavior (properties and method). Forexample: car, pen, bike,
chair, glass, keyboard, monitor etc.
In JavaScript, objects are king. If you understand objects, you understand JavaScript.
Objects in Javascript
Last Updated: 29-06-2020
Objects, in JavaScript, is it’s most important data-type and forms the building blocks for modern
JavaScript. These objects are quite different from JavaScript’s primitive data-types(Number,
String, Boolean, null, undefined and symbol) in the sense that while these primitive data-types all
store a single value each (depending on their types).
Objects are more complex and each object may contain any combination of these primitive
data-types as well as reference data-types.
An object, is a reference data type. Variables that are assigned a reference value are given
a reference or a pointer to that value. That reference or pointer points to the location in
memory where the object is stored. The variables don’t actually store the value.
Loosely speaking, objects in JavaScript may be de ned as an unordered collection of
related data, of primitive or reference types, in the form of “key: value” pairs. These keys
can be variables or functions and are called properties and methods, respectively, in the
context of an object.
An object can be created with figure brackets {…} with an optional list of properties. A property is a
“key: value” pair, where a key is a string (also called a “property name”), and value can be
anything.
To understand this rather abstract definition, let us look at an example of a JavaScript Object :
let school = {
name : "Vivekananda School",
location : "Delhi",
established : "1971"
}
In the above example “name”, “location”, “established” are all “keys” and “Vivekananda
School”, “Delhi” and 1971 are values of these keys respectively.
Each of these keys is referred to as properties of the object. An object in JavaScript may also have
a function as a member, in which case it will be known as a method of that object.
[Link] 1/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Output:
In the above example, “displayinfo” is a method of the school object that is being used to work
with the object’s data, stored in its properties.
[Link] 2/17
12/20/2020 Objects in Javascript - GeeksforGeeks
The property names can be strings or numbers. In case the property names are numbers, they
must be accessed using the “bracket notation” like this :
let school = {
name: 'Vivekananda School',
location : 'Delhi',
established : '1971',
20 : 1000,
displayInfo : function(){
[Link](`The value of the key 20 is ${school['20']}`);
}
}
[Link]();
Output:
Property names can also be strings with more than one space separated words. In which case,
these property names must be enclosed in quotes :
let school = {
"school name" : "Vivekananda School",
}
Like property names which are numbers, they must also be accessed using the bracket notation.
Like if we want to access the ‘Vivekananda’ from ‘Vivekananda School’ we can do something like
this:
[Link] 3/17
12/20/2020 Objects in Javascript - GeeksforGeeks
// bracket notation
let school = {
name: 'Vivekananda School',
displayInfo : function(){
[Link](`${[Link](' ')[0]}`);
}
}
[Link](); // Vivekananda
Output:
In the above code, we made use of bracket notation and also split method provided by javascript
which you will learn about in strings article.
Inherited Properties
[Link] 4/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Inherited properties of an object are those properties which have been inherited from the object’s
prototype, as opposed to being defined for the object itself, which is known as the object’s Own
property. To verify if a property is an objects Own property, we can use the hasOwnProperty method.
Property Attributes
Data properties in JavaScript have four attributes.
// hasOwnProperty code in js
const object1 = new Object();
object1.property1 = 42;
[Link]([Link]('property1')); // true
Output:
Creating Objects
There are several ways or syntax’s to create objects. One of which, known as the Object literal
syntax, we have already used. Besides the object literal syntax, objects in JavaScript may also be
created using the constructors, Object Constructor or the prototype pattern.
[Link] 5/17
12/20/2020 Objects in Javascript - GeeksforGeeks
1. Using the Object literal syntax : Object literal syntax uses the {…} notation to initialize an
object an its methods/properties directly.
Let us look at an example of creating objects using this method :
var obj = {
member1 : value1,
member2 : value2,
};
These members can be anything – strings, numbers, functions, arrays or even other objects.
An object like this is referred to as an object literal. This is different from other methods of
object creation which involve using constructors and classes or prototypes, which have been
discussed below.
2. Object Constructor : Another way to create objects in JavaScript involves using the
“Object” constructor. The Object constructor creates an object wrapper for the given value.
This, used in conjunction with the “new” keyword allows us to initialize new objects.
Example :
[Link] = function(){
[Link](`${[Link]} was established
in ${[Link]} at ${[Link]}`);
}
[Link]();
[Link] 6/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Output:
The two methods mentioned above are not well suited to programs that require the creation
of multiple objects of the same kind, as it would involve repeatedly writing the above lines of
code for each such object. To deal with this problem, we can make use of two other methods
of object creation in JavaScript that reduces this burden significantly, as mentioned below:
Output:
Notice the usage of the “new” keyword before the function Vehicle. Using the “new” keyword
in this manner before any function turns it into a constructor. What the “new Vehicle()”
actually does is :
It creates a new object and sets the constructor property of the object to schools (It is
important to note that this property is a special default property that is not
[Link] 7/17
12/20/2020 Objects in Javascript - GeeksforGeeks
class people {
constructor()
{
[Link] = "Adam";
}
}
// Output : Adam
[Link]([Link]);
Output:
Having more than one function in a class with the name of constructor() results in an error.
4. Prototypes : Another way to create objects involves using prototypes. Every JavaScript
function has a prototype object property by default(it is empty by default). Methods or
properties may be attached to this property. A detailed description of prototypes is beyond
the scope of this introduction to objects.
However you may familiarize yourself with the basic syntax used as below:
let obj = [Link](prototype_object, propertiesObject)
// the second propertiesObject argument is optional
[Link] 8/17
12/20/2020 Objects in Javascript - GeeksforGeeks
let footballers = {
position: "Striker"
}
// Output : Striker
[Link]([Link]);
Output:
In the above example footballers served as a prototype for creating the object “footballer1”.
All objects created in this way inherits all properties and methods from its prototype objects.
Prototypes can have prototypes and those can have prototypes and so on. This is referred to
as prototype chaining in JavaScript. This chain terminates with the [Link] which is
the default prototype fallback for all objects. Javascript objects, by default, inherit properties
and methods from [Link] but these may easily be overridden. It is also interesting
to note that the default prototype is not always [Link] example Strings and
Arrays have their own default prototypes – [Link] and [Link]
respectively.
[Link] 9/17
12/20/2020 Objects in Javascript - GeeksforGeeks
1. dot notation :
([Link])
let school = {
name : "Vivekanada",
location : "Delhi",
established : 1971,
20 : 1000,
displayinfo : function() {
[Link](`${[Link]} was established
in ${[Link]} at ${[Link]}`);
}
[Link]([Link]);
[Link]([Link]);
Output:
2. Bracket Notation :
objectName["memberName"]
let school = {
name : "Vivekanada School",
location : "Delhi",
established : 1995,
20 : 1000,
displayinfo : function() {
[Link](`${[Link]} was established
in ${[Link]} at ${[Link]}`);
}
}
// Output: 1000
[Link](school['20']);
[Link] 10/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Output:
Unlike the dot notation, the bracket keyword works with any string combination, including, but not
limited to multi-word strings.
For example:
Unlike the dot notation, the bracket notation can also contain names which are results of any
expressions variables whose values are computed at run-time.
For instance :
Similar operations are not possible while using the dot notation.
To iterate over all existing enumerable keys of an object, we may use the for...in construct. It is
worth noting that this allows us to access only those properties of an object which are enumerable
(Recall that enumerable is one of the four attributes of data properties).
For instance, properties inherited from the [Link] are not enumerable. But, enumerable
properties inherited from somewhere can also be accessed using the for...in construct
Example:
let person = {
gender : "male"
}
// and gender
[Link](key);
}
Output:
Deleting Properties
To Delete a property of an object we can make use of the delete operator. An example of its usage
has been listed below:
let obj1 = {
propfirst : "Name"
}
// Output : Name
[Link]([Link]);
delete [Link]
// Output : undefined
[Link]([Link]);
Output:
[Link] 12/17
12/20/2020 Objects in Javascript - GeeksforGeeks
It is important to note that we can not delete inherited properties or non-configurable properties
in this manner.
For example :
let obj1 = {
propfirst : "Name"
}
// Output : Name
[Link]([Link])
let obj2 = [Link](obj1);
// Output : Name
[Link]([Link]);
// Output : true.
[Link](delete [Link]);
// Output : Name
[Link]([Link]);
Output:
[Link] 13/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Recommended Posts:
Extract unique objects by attribute from array of objects.
JavaScript Course | Objects in JavaScript
How to compare two JavaScript array objects using jQuery/JavaScript ?
How to merge properties of two JavaScript objects dynamically?
[Link] 14/17
12/20/2020 Objects in Javascript - GeeksforGeeks
D aipayan
Check out this Author's contributed articles.
If you like GeeksforGeeks and would like to contribute, you can also write an article using
[Link] or mail your article to contribute@[Link]. See your
article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button
below.
Improved By : immukul
[Link] 15/17
12/20/2020 Objects in Javascript - GeeksforGeeks
2.3
To-do Done
Based on 3 vote(s)
Improve Article
Please write to us at contribute@[Link] to report any issue with the above content.
Writing code in comment? Please use [Link], generate link and share the link here.
Load Comments
feedback@[Link]
Company Learn
About Us Algorithms
Contact Us CS Subjects
Video Tutorials
Practice Contribute
[Link] 16/17
12/20/2020 Objects in Javascript - GeeksforGeeks
Courses Write an Article
Company-wise Write Interview Experience
Topic-wise Internships
[Link] 17/17
12/20/2020 JavaScript Objects - javatpoint
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)
<script> ⇧
[Link] 1/6
12/20/2020 JavaScript Objects - javatpoint
emp={id:102,name:"Shyam Kumar",salary:40000}
[Link]([Link]+" "+[Link]+" "+[Link]);
[Link]="Ravi Malik";
[Link] 2/6
12/20/2020 JavaScript Objects - javatpoint
function emp(id,name,salary){
[Link]=id;
[Link]=salary;
function emp(id,name,salary){
[Link]=salary;
function changeSalary(otherSalary){
[Link] 3/6
12/20/2020 JavaScript Objects - javatpoint
1 [Link]() This method is used to copy enumerable and own properties from a source object to
a target object
2 [Link]() This method is used to create a new object with the specified prototype object and
properties.
3 [Link]() This method is used to describe some behavioral attributes of the property.
5 [Link]() This method returns an array with arrays of the key, value pairs.
7 [Link]() This method returns a property descriptor for the specified property of the specified
object.
8 [Link]() This method returns all own property descriptors of a given object.
9 [Link]() This method returns an array of all properties (enumerable or not) found.
10 [Link]() This method returns an array of all own symbol key properties.
12 [Link]() This method determines whether two values are the same value.
16 [Link]() This method returns an array of a given object's own property names.
18 [Link]() This method prevents new properties from being added and marks all existing
properties as non-configurable.
19 [Link]() This method sets the prototype of a specified object to another object.
← prev next →
[Link] 4/6
12/15/2020 JavaScript Functions
[Link] LOG IN
OPEN
100% Placement Assistance
JavaScript Functions
❮ Previous Next ❯
Example
Try it Yourself »
Function names can contain letters, digits, underscores, and dollar signs (same rules as
variables).
[Link] 1/11
12/15/2020 JavaScript Functions
Function parameters are listed inside the parentheses () in the function definition.
Function arguments are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
Function Invocation
The code inside the function will execute when "something" invokes (calls) the function:
You will learn a lot more about function invocation later in this tutorial.
[Link] 2/11
12/15/2020 JavaScript Functions
Function Return
When JavaScript reaches a return statement, the function will stop executing.
If the function was invoked from a statement, JavaScript will "return" to execute the
code after the invoking statement.
Functions often compute a return value. The return value is "returned" back to the
"caller":
Example
Calculate the product of two numbers, and return the result:
function myFunction(a, b) {
return a * b; // Function returns the product of a and b
}
12
Try it Yourself »
Why Functions?
You can reuse code: Define the code once, and use it many times.
You can use the same code many times with different arguments, to produce different
results.
Example
Convert Fahrenheit to Celsius:
[Link] 3/11
12/15/2020 JavaScript Functions
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius(77);
Try it Yourself »
Accessing a function without () will return the function object instead of the function
result.
Example
function toCelsius(fahrenheit) {
return (5/9) * (fahrenheit-32);
}
[Link]("demo").innerHTML = toCelsius;
Try it Yourself »
Example
Instead of using a variable to store the return value of a function:
[Link] 4/11
12/15/2020 JavaScript Functions
var x = toCelsius(77);
var text = "The temperature is " + x + " Celsius";
Try it Yourself »
You will learn a lot more about functions later in this tutorial.
Local Variables
Variables declared within a JavaScript function, become LOCAL to the function.
Example
function myFunction() {
var carName = "Volvo";
// code here CAN use carName
}
Try it Yourself »
Since local variables are only recognized inside their functions, variables with the same
name can be used in different functions.
[Link] 5/11
12/15/2020 JavaScript Functions
Local variables are created when a function starts, and deleted when the function is
completed.
Exercise:
Execute the function named myFunction .
function myFunction() {
alert("Hello World!");
}
;
Submit Answer »
❮ Previous Next ❯
[Link] 6/11
JavaScript Form Validation:
It is important to validate the form submitted by the user because it can have inappropriate
values. So, validation is must to authenticate user. JavaScript provides facility to validate the
form on the client-side so data processing will be faster than server-side validation. Most of the
web developers prefer JavaScript form validation. Through JavaScript, we can validate name,
password, email, date, mobile numbers and more fields.