SlideShare a Scribd company logo
Java Script Objects
Objects
● An object is an unordered collection of properties, each of
which has a name and a value.
● Property names are strings, so objects map strings to
values.
● In addition to maintaining its own set of properties, a
JavaScript object also inherits the properties of its
“prototype” object.
● JavaScript objects are dynamic—properties can usually be
added and deleted
● Objects are mutable and are manipulated by reference
rather than by value.
Creating Objects
● Objects can be created with object literals, with the new keyword,
and (in ECMAScript 5) with the Object.create() function.
● An object literal is a comma-separated list of colon-separated
properties (name:value pairs), enclosed within curly braces
●
A property name is a JavaScript identifier or a string literal (the
empty string is allowed).
● A property value is any JavaScript expression; the value of the
expression (it may be a primitive value or an object value)
becomes the value of the property.
Creating Objects
● Examples
● var empty = {}; // An object with no properties
● var point = { x:0, y:0 }; // Two properties
● // With more complex properties
var point2 = { x:point.x, y:point.y+1 };
● // Nonidentifier property names are quoted
var book = { "main title": "JavaScript", // space in property nam
'sub-title': "Pocket Ref", // punctuation in name
"for": "all audiences", // reserved word name
};
Creating Objects with new
● The new operator creates and initializes a new
object.
● The new keyword must be followed by a
function invocation (such functions is called a
constructor and serves to initialize a newly
created object).
● Core JavaScript includes built-in constructors
for native types, own constructor functions can
be defined to initialize newly created objects.
Creating Objects with new
● Examples
– var o = new Object(); // An empty object: same as
{}.
– var a = new Array(); // An empty array: same as [].
– var d = new Date (); //A Date for the current time.
– var r = new RegExp("js"); // A pattern matching
object.
Prototype Object
● Every Java-Script object has a second JavaScript
object (or null, rarely) associated with it, called as
Prototype, from which the properties are inherited
● All objects created by object literals have the same
prototype object refered in code :
Object.prototype
● Objects created using the new keyword and a
constructor invocation use the value of the
prototype property of the constructor function
as their prototype.
Prototype Object
● Object created by new Object() inherits from Object.prototype
just as the object created by {} does.
● The object created by new Array() uses Array.prototype as its
prototype, and the object created by new Date() uses
Date.prototype as its prototype.
● Object.prototype is one of the rare objects that has no
prototype: it does not inherit any properties.
● All other prototype objects inherit from Object.prototype object, so
the objects created using other objects like Date(), Array() etc
inherit from both the corresponding prototype object and
Object.prototype (prototype chain).
Creating Objects using
Object.create()
● Object.create(), creates a new object, using
its first argument as the prototype of that
object.
● Object.create() also takes an optional second
argument that describes the properties of
the new object.
● Object.create() is a static function, not a
method invoked on individual objects.
Creating Objects using
Object.create()
● Example
– // o1 inherits properties x and y.
var o1 = Object.create({x:1, y:2});
– // o2 inherits no properties or methods, no basic
methods will works as nothing is inherited
var o2 = Object.create(null);
– // o3 is like {} or new Object().
var o3 = Object.create(Object.prototype);
Objects
● Objects have attributes and methods.
● Many pre-defined objects and object types
exist.
● Using objects follows the syntax of C++/Java:
– objectname.attributename
– objectname.methodname()
The document object
● Many attributes of the current document are
available via the document object:
– Title
– Referrer
– URL
– Images
– Forms
– Links
– Colors
document Methods
● document.write() – the output goes into the
HTML document.
– document.write("My title is" + document.title);
● document.writeln() - adds a newline after
printing.
The navigator Object
● Represents the browser and is a Read-only
● Attributes include:
– appName
– appVersion
– platform
navigator Example
if (navigator.appName == "Microsoft Internet
Explorer") {
document.writeln("<H1>This page
requires Netscape!</H1>");
}
The window Object
● Represents the current window.
● There are possible many objects of type
Window, the predefined object window
represents the current window.
● Access to, and control of, a number of
properties including position and size.
window attributes and methods
● Attributes
– document
– name
– Status ( the status
line)
– Parent
● Methods
– Alert()
– Close()
– Prompt()
– MoveTo()
– MoveBy()
– Open()
– scroll()
– ScrollTo()
– resizeBy()
– resizeTo()
String Object
● A string is an immutable ordered sequence of 16-bit
values, each of which represents a Unicode
character - strings are JavaScript’s type for
representing text.
● JavaScript does not have a special type that
represents a single character of a string – To
represent a single 16-bit value, we need to use a
string that has a length of 1.
● Double-quote characters may be contained within
strings delimited by single-quote characters, and
single-quote characters may be contained within
strings delimited by double quotes
String Object
● "" // The empty string: it has zero characters;
● ' name="myform" '
● "Wouldn't you prefer O'Reilly's book?"
● "This stringnhas two lines"
● "π = 3.14"
Escape Sequences
● Backslash () is used to represent escape
sequences
● xYY - The Latin-1 character rep by two
hexadecimal digits XX
● uXXXX - The Unicode character specified by
the four hexadecimal digits XXXX
JavaScript escape sequences
●
Sequence Character represented
●
0 The NUL character (u0000)
●
b Backspace (u0008)
●
t Horizontal tab (u0009)
● n Newline (u000A)
● v Vertical tab (u000B)
● f Form feed (u000C)
● r Carriage return (u000D)
● " Double quote (u0022)
● ' Apostrophe or single quote (u0027)
●  Backslash (u005C)
String Concatenation & String
Length
● String Concatenation is supported by +
operator
● msg = "Hello, " + "world"; // => "Hello, world"
● To determine the length of a string, the
number of 16-bit values it contains, is retrieved
using the length property of the string -
s.length
String Methods
● var s = "hello, world"
● s.charAt(0)
● s.charAt(s.length-1)
● s.substring(1,4)
● s.slice(1,4)
● s.slice(-3)
● s.indexOf("l")
● s.lastIndexOf("l")
● s.indexOf("l", 3)
● s.split(", ")
● s.replace("h", "H")
● s.toUpperCase()
● //Start with some text as example
● => "h": the first character.
● => "d": the last character.
● => "ell": chars 2, 3, and 4
● => "ell": same thing
● => "rld": last 3 characters
● => 2: position of first l.
● => 10: position of last l.
● => 3: position at or after 3
● => ["hello", "world"]
● => "Hello, world":
● replaces all instances
● => "HELLO, WORLD"
Immutable Property of Strings
●
Strings are immutable in JavaScript.
●
Methods like replace() and toUpperCase() return new strings: they
do not modify the string on which they are invoked.
●
In ECMAScript 5, strings can be treated like read-only arrays, and
we can access individual characters (16-bit values) from a string
using square brackets instead of the charAt() method:
●
s = "hello, world";
●
s[0] // => "h"
●
s[s.length-1] // => "d"
String to Numbers Conversion
● Global Functions
– parseInt()
● parses only integers
● If a string begins with “0x” or “0X,” parseInt() interprets it as a hexadecimal
number.
● It accepts an optional second argument specifying the radix (base) of the
number to be parsed. (2 to 36)
– parseFloat() - parses both integers and floating-point numbers.
– Both functions skip leading whitespace, parse as many numeric
characters as they can, and ignore anything that follows.
– If the first nonspace character is not part of a valid numeric literal,
they return NaN
String to Numbers Conversion
● Examples
– parseInt("3 blind mice") // => 3
– parseFloat(" 3.14 meters") // => 3.14
– parseInt("-12.34") // => -12
– parseInt("0xFF") // => 255
– parseFloat("$72.47"); // => NaN
– parseInt("11", 2); // => 3 (1*2 + 1)
– parseInt("077", 8); // => 63 (7*8 + 7)
– parseInt("ff", 16); // => 255 (15*16 + 15)
Number Conversion to String
● var n = 123456.789;
● n.toFixed(2); // "123456.79"
● n.toExponential(3); // "1.235e+5"
● n.toPrecision(7); // "123456.8"
toString()
● The toString() method defined by the Number class
accepts an optional argument that specifies a radix, or
base, for the conversion. If not specified the conversion is
done in base 10.
● Example
– var n = 17;
– binary_string = n.toString(2); // Evaluates to "10001"
– octal_string = "0" + n.toString(8); // Evaluates to "021"
– hex_string = "0x" + n.toString(16); // Evaluates to "0x11"
Math Object
● JavaScript supports more complex
mathematical operations through a set of
functions and constants defined as properties
of the Math object
Math functions and Properties
● Math.pow(2,53) //=> 9007199254740992: 2 to the power 53
● Math.round(.6) //=> 1.0: round to the nearest integer
● Math.ceil(.6) //=> 1.0: round up to an integer
● Math.floor(.6) //=> 0.0: round down to an integer
● Math.abs(-5) //=> 5: absolute value
● Math.max(x,y,z) //Return the largest argument
● Math.min(x,y,z) //Return the smallest argument
●
Math.random() //Pseudo-random number 0 <= x < 1.0
● Math.PI // π
● Math.E // e: The base of the natural logarithm
Math functions and Properties
● Math.sqrt(3) // The square root of 3
● Math.pow(3,1/3) // The cube root of 3
● Math.sin(0) // Trig: also Math.cos, Math.atan, etc.
● Math.log(10) // Natural logarithm of 10
● Math.log(100)/Math.LN10 // Base 10 logarithm of 100
● Math.log(512)/Math.LN2 // Base 2 logarithm of 512
● Math.exp(3) // Math.E cubed
Infinity
● Arithmetic in JavaScript does not raise errors in cases of
overflow, underflow, or division by zero.
● When the result of a numeric operation is larger than the
largest representable number (overflow), the result is
Infinity.
● Similarly, when a negative value becomes larger than the
largest representable negative number, the result is negative
infinity, printed as -Infinity.
● When adding, subtracting, multiplying, or dividing Infinity by
anything results in an infinite value (possibly with the
sign reversed).
NaN
● The not-a-number value has a feature in JavaScript: it does not
compare equal to any other value, including itself.
● x == NaN to determine whether the value of a variable x is NaN.
Instead, you should write x != x, returns true if, and only if, x is
NaN.
●
The function
– isNaN() - returns true if its argument is NaN, or if that argument is
a nonnumeric value such as a string or an object.
– isFinite() returns true if its argument is a number other than NaN,
Infinity, or -Infinity
Type Conversions
● Implicit Conversion
– Boolean conversion as false for :
● undefined
● null
● 0
● -0
● NaN
● "" // the empty string
– Boolean conversion to true - All other values, including
all objects (and arrays)
Type Conversions
● Implicit Conversion - Examples
– 10 + " objects" // => "10 objects". 10 -> string
– "7" * "4" // => 28: both strings -> numbers
– var n = 1 – "x"; // => NaN: "x" can't convert to a number
– n + " objects" // => "NaN objects": NaN -> "NaN"
– Following comparisons are true, after conversion
● null == undefined //These two are treated as equal.
● "0" == 0 // String -> a number before comparing.
● 0 == false //Boolean -> number before comparing.
● "0" == false //Both operands -> 0 before comparing.
Type Conversions
●
Implicit Conversion
●
If one operand of the + operator is a string, it converts the other
one to a string.
●
The unary + operator converts its operand to a number.
●
And the unary ! operator converts its operand to a boolean and
negates it.
●
Examples
– x + "" // Same as String(x)
– +x // Same as Number(x).
– x-0 // Same as Number(x).
– !x // Same as Boolean(x)
javascript objects
javascript objects
Type Conversions
● Explicit Conversion – done using the
Boolean(), Number(), String(), or Object()
functions:
– Number("3") // => 3
– String(false) // => "false" Or false.toString()
– Boolean([]) // => true
– Object(3) // => new Number(3)
Undeclared Variables
● Assigning a value to an undeclared variable,
Java-Script actually creates that variable as a
property of the global object, and it works
like a properly declared global variable
● Best Practise – to declare the variables using
'var'
Array Objects
● Arrays are supported as objects.
● Attribute length
● Methods include: concat, join, pop, push,
reverse, sort
EIW: Javascript the Language 42
Some similarity to C++
• Array indexes start at 0.
• Syntax for accessing an element is the
same:
a[3]++;
b[i] = i*72;
EIW: Javascript the Language 43
New in JS
• Arrays can grow dynamically – just add
new elements at the end.
• Arrays can have holes, elements that
have no value.
• Array elements can be anything
– numbers, strings, or arrays!
EIW: Javascript the Language 44
Creating Array Objects
• With the new operator and a size:
var x = new Array(10);
• With the new operator and an initial set
of element values:
var y = new Array(18,”hi”,22);
• Assignment of an array literal
var x = [1,0,2];
EIW: Javascript the Language 45
Arrays and Loops
var a = new Array(4);
for (i=0;i<a.length;i++) {
a[i]=i;
}
for (j in a) {
document.writeln(j);
}
EIW: Javascript the Language 46
Array Example
var colors = [ “blue”,
“green”,
“yellow];
var x = window.prompt(“enter a
number”);
window.bgColor = colors[x];
EIW: Javascript the Language 47
Array of Arrays
• Javascript does not support
2-dimensional arrays (as part of the
language).
• BUT – each array element can be an
array.
• Resulting syntax looks like C++!
EIW: Javascript the Language 48
Array of Arrays Example
var board = [ [1,2,3],
[4,5,6],
[7,8,9] ];
for (i=0;i<3;i++)
for (j=0;j<3;j++)
board[i][j]++;

More Related Content

What's hot (20)

Event In JavaScript
Event In JavaScriptEvent In JavaScript
Event In JavaScript
ShahDhruv21
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
sentayehu
 
Database Connectivity in PHP
Database Connectivity in PHPDatabase Connectivity in PHP
Database Connectivity in PHP
Taha Malampatti
 
Servlets
ServletsServlets
Servlets
Akshay Ballarpure
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
Jesus Obenita Jr.
 
Dom
DomDom
Dom
Rakshita Upadhyay
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
JSON: The Basics
JSON: The BasicsJSON: The Basics
JSON: The Basics
Jeff Fox
 
PHP FUNCTIONS
PHP FUNCTIONSPHP FUNCTIONS
PHP FUNCTIONS
Zeeshan Ahmed
 
Javascript essentials
Javascript essentialsJavascript essentials
Javascript essentials
Bedis ElAchèche
 
Lab #2: Introduction to Javascript
Lab #2: Introduction to JavascriptLab #2: Introduction to Javascript
Lab #2: Introduction to Javascript
Walid Ashraf
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
baabtra.com - No. 1 supplier of quality freshers
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
Karmatechnologies Pvt. Ltd.
 
Java Server Pages(jsp)
Java Server Pages(jsp)Java Server Pages(jsp)
Java Server Pages(jsp)
Manisha Keim
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Arrays in Java
Arrays in JavaArrays in Java
Arrays in Java
Naz Abdalla
 
Java Servlets
Java ServletsJava Servlets
Java Servlets
BG Java EE Course
 
Javascript
JavascriptJavascript
Javascript
mussawir20
 
Networking in Java
Networking in JavaNetworking in Java
Networking in Java
Tushar B Kute
 

Viewers also liked (20)

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
JavaScript and OOP
JavaScript and OOPJavaScript and OOP
JavaScript and OOP
easelsolutions
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
Borey Lim
 
學習JavaScript_Dom
學習JavaScript_Dom學習JavaScript_Dom
學習JavaScript_Dom
俊彬 李
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basics
Net7
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
baabtra.com - No. 1 supplier of quality freshers
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
JavaScript regular expression
JavaScript regular expressionJavaScript regular expression
JavaScript regular expression
Hernan Mammana
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
Mayur Mudgal
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
Jesus Obenita Jr.
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
rahul kundu
 
DOM ( Document Object Model )
DOM ( Document Object Model )DOM ( Document Object Model )
DOM ( Document Object Model )
ITSTB
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
Brian Moschel
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
Let Search Power Your Intranet!
Let Search Power Your Intranet!Let Search Power Your Intranet!
Let Search Power Your Intranet!
Ravi Mynampaty
 
Javascript
JavascriptJavascript
Javascript
Sun Technlogies
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
Reem Alattas
 
Introduction to Regular Expressions
Introduction to Regular ExpressionsIntroduction to Regular Expressions
Introduction to Regular Expressions
Matt Casto
 
Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
Dhananjay Kumar
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
Borey Lim
 
學習JavaScript_Dom
學習JavaScript_Dom學習JavaScript_Dom
學習JavaScript_Dom
俊彬 李
 
Javascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basicsJavascript, DOM, browsers and frameworks basics
Javascript, DOM, browsers and frameworks basics
Net7
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
Reem Alattas
 
JavaScript regular expression
JavaScript regular expressionJavaScript regular expression
JavaScript regular expression
Hernan Mammana
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
Mohammed Arif
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
Mayur Mudgal
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
Ravi Bhadauria
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
rahul kundu
 
DOM ( Document Object Model )
DOM ( Document Object Model )DOM ( Document Object Model )
DOM ( Document Object Model )
ITSTB
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
Mindy McAdams
 
Let Search Power Your Intranet!
Let Search Power Your Intranet!Let Search Power Your Intranet!
Let Search Power Your Intranet!
Ravi Mynampaty
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
Reem Alattas
 
Introduction to Regular Expressions
Introduction to Regular ExpressionsIntroduction to Regular Expressions
Introduction to Regular Expressions
Matt Casto
 
Ad

Similar to javascript objects (20)

JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
KennyPratheepKumar
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
Java script summary
Java script summaryJava script summary
Java script summary
maamir farooq
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
jason hu 金良胡
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Javascript
JavascriptJavascript
Javascript
Prashant Kumar
 
WEB222-lecture-4.pptx
WEB222-lecture-4.pptxWEB222-lecture-4.pptx
WEB222-lecture-4.pptx
RohitSharma318779
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Rangana Sampath
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
Uchitha Bandara
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Javascript
JavascriptJavascript
Javascript
theacadian
 
Javascript
JavascriptJavascript
Javascript
20261A05H0SRIKAKULAS
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
yoavrubin
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
JavaScript Core
JavaScript CoreJavaScript Core
JavaScript Core
François Sarradin
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
Front end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript coreFront end fundamentals session 1: javascript core
Front end fundamentals session 1: javascript core
Web Zhao
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Rangana Sampath
 
Object oriented javascript
Object oriented javascriptObject oriented javascript
Object oriented javascript
Usman Mehmood
 
3.1 javascript objects_DOM
3.1 javascript objects_DOM3.1 javascript objects_DOM
3.1 javascript objects_DOM
Jalpesh Vasa
 
Scalable JavaScript
Scalable JavaScriptScalable JavaScript
Scalable JavaScript
Ynon Perek
 
1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications1-JAVA SCRIPT. servere-side applications vs client side applications
1-JAVA SCRIPT. servere-side applications vs client side applications
surajshreyans
 
JavaScript OOPS Implimentation
JavaScript OOPS ImplimentationJavaScript OOPS Implimentation
JavaScript OOPS Implimentation
Usman Mehmood
 
JavaScript - Programming Languages course
JavaScript - Programming Languages course JavaScript - Programming Languages course
JavaScript - Programming Languages course
yoavrubin
 
ES2015 (ES6) Overview
ES2015 (ES6) OverviewES2015 (ES6) Overview
ES2015 (ES6) Overview
hesher
 
13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript13_User_Defined_Objects.pptx objects in javascript
13_User_Defined_Objects.pptx objects in javascript
tayyabbiswas2025
 
Ad

Recently uploaded (20)

Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Agentic AI - The New Era of Intelligence
Agentic AI - The New Era of IntelligenceAgentic AI - The New Era of Intelligence
Agentic AI - The New Era of Intelligence
Muzammil Shah
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Nix(OS) for Python Developers - PyCon 25 (Bologna, Italia)
Peter Bittner
 
Let’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack CommunityLet’s Get Slack Certified! 🚀- Slack Community
Let’s Get Slack Certified! 🚀- Slack Community
SanjeetMishra29
 
Jeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software DeveloperJeremy Millul - A Talented Software Developer
Jeremy Millul - A Talented Software Developer
Jeremy Millul
 
Microsoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentationMicrosoft Build 2025 takeaways in one presentation
Microsoft Build 2025 takeaways in one presentation
Digitalmara
 
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AI Emotional Actors:  “When Machines Learn to Feel and Perform"AI Emotional Actors:  “When Machines Learn to Feel and Perform"
AI Emotional Actors: “When Machines Learn to Feel and Perform"
AkashKumar809858
 
Maxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing placeMaxx nft market place new generation nft marketing place
Maxx nft market place new generation nft marketing place
usersalmanrazdelhi
 
Improving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevExImproving Developer Productivity With DORA, SPACE, and DevEx
Improving Developer Productivity With DORA, SPACE, and DevEx
Justin Reock
 
New Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDBNew Ways to Reduce Database Costs with ScyllaDB
New Ways to Reduce Database Costs with ScyllaDB
ScyllaDB
 
Measuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI SuccessMeasuring Microsoft 365 Copilot and Gen AI Success
Measuring Microsoft 365 Copilot and Gen AI Success
Nikki Chapple
 
Dev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API WorkflowsDev Dives: System-to-system integration with UiPath API Workflows
Dev Dives: System-to-system integration with UiPath API Workflows
UiPathCommunity
 
Contributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptxContributing to WordPress With & Without Code.pptx
Contributing to WordPress With & Without Code.pptx
Patrick Lumumba
 
Gihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai TechnologyGihbli AI and Geo sitution |use/misuse of Ai Technology
Gihbli AI and Geo sitution |use/misuse of Ai Technology
zainkhurram1111
 
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk TechniciansOffshore IT Support: Balancing In-House and Offshore Help Desk Technicians
Offshore IT Support: Balancing In-House and Offshore Help Desk Technicians
john823664
 
Agentic AI - The New Era of Intelligence
Agentic AI - The New Era of IntelligenceAgentic AI - The New Era of Intelligence
Agentic AI - The New Era of Intelligence
Muzammil Shah
 
Introducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRCIntroducing the OSA 3200 SP and OSA 3250 ePRC
Introducing the OSA 3200 SP and OSA 3250 ePRC
Adtran
 
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Agentic AI Explained: The Next Frontier of Autonomous Intelligence & Generati...
Aaryan Kansari
 
Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025Kubernetes Cloud Native Indonesia Meetup - May 2025
Kubernetes Cloud Native Indonesia Meetup - May 2025
Prasta Maha
 
UiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build PipelinesUiPath Community Zurich: Release Management and Build Pipelines
UiPath Community Zurich: Release Management and Build Pipelines
UiPathCommunity
 
Fortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in CybersecurityFortinet Certified Associate in Cybersecurity
Fortinet Certified Associate in Cybersecurity
VICTOR MAESTRE RAMIREZ
 
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptxECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
ECS25 - The adventures of a Microsoft 365 Platform Owner - Website.pptx
Jasper Oosterveld
 

javascript objects

  • 2. Objects ● An object is an unordered collection of properties, each of which has a name and a value. ● Property names are strings, so objects map strings to values. ● In addition to maintaining its own set of properties, a JavaScript object also inherits the properties of its “prototype” object. ● JavaScript objects are dynamic—properties can usually be added and deleted ● Objects are mutable and are manipulated by reference rather than by value.
  • 3. Creating Objects ● Objects can be created with object literals, with the new keyword, and (in ECMAScript 5) with the Object.create() function. ● An object literal is a comma-separated list of colon-separated properties (name:value pairs), enclosed within curly braces ● A property name is a JavaScript identifier or a string literal (the empty string is allowed). ● A property value is any JavaScript expression; the value of the expression (it may be a primitive value or an object value) becomes the value of the property.
  • 4. Creating Objects ● Examples ● var empty = {}; // An object with no properties ● var point = { x:0, y:0 }; // Two properties ● // With more complex properties var point2 = { x:point.x, y:point.y+1 }; ● // Nonidentifier property names are quoted var book = { "main title": "JavaScript", // space in property nam 'sub-title': "Pocket Ref", // punctuation in name "for": "all audiences", // reserved word name };
  • 5. Creating Objects with new ● The new operator creates and initializes a new object. ● The new keyword must be followed by a function invocation (such functions is called a constructor and serves to initialize a newly created object). ● Core JavaScript includes built-in constructors for native types, own constructor functions can be defined to initialize newly created objects.
  • 6. Creating Objects with new ● Examples – var o = new Object(); // An empty object: same as {}. – var a = new Array(); // An empty array: same as []. – var d = new Date (); //A Date for the current time. – var r = new RegExp("js"); // A pattern matching object.
  • 7. Prototype Object ● Every Java-Script object has a second JavaScript object (or null, rarely) associated with it, called as Prototype, from which the properties are inherited ● All objects created by object literals have the same prototype object refered in code : Object.prototype ● Objects created using the new keyword and a constructor invocation use the value of the prototype property of the constructor function as their prototype.
  • 8. Prototype Object ● Object created by new Object() inherits from Object.prototype just as the object created by {} does. ● The object created by new Array() uses Array.prototype as its prototype, and the object created by new Date() uses Date.prototype as its prototype. ● Object.prototype is one of the rare objects that has no prototype: it does not inherit any properties. ● All other prototype objects inherit from Object.prototype object, so the objects created using other objects like Date(), Array() etc inherit from both the corresponding prototype object and Object.prototype (prototype chain).
  • 9. Creating Objects using Object.create() ● Object.create(), creates a new object, using its first argument as the prototype of that object. ● Object.create() also takes an optional second argument that describes the properties of the new object. ● Object.create() is a static function, not a method invoked on individual objects.
  • 10. Creating Objects using Object.create() ● Example – // o1 inherits properties x and y. var o1 = Object.create({x:1, y:2}); – // o2 inherits no properties or methods, no basic methods will works as nothing is inherited var o2 = Object.create(null); – // o3 is like {} or new Object(). var o3 = Object.create(Object.prototype);
  • 11. Objects ● Objects have attributes and methods. ● Many pre-defined objects and object types exist. ● Using objects follows the syntax of C++/Java: – objectname.attributename – objectname.methodname()
  • 12. The document object ● Many attributes of the current document are available via the document object: – Title – Referrer – URL – Images – Forms – Links – Colors
  • 13. document Methods ● document.write() – the output goes into the HTML document. – document.write("My title is" + document.title); ● document.writeln() - adds a newline after printing.
  • 14. The navigator Object ● Represents the browser and is a Read-only ● Attributes include: – appName – appVersion – platform
  • 15. navigator Example if (navigator.appName == "Microsoft Internet Explorer") { document.writeln("<H1>This page requires Netscape!</H1>"); }
  • 16. The window Object ● Represents the current window. ● There are possible many objects of type Window, the predefined object window represents the current window. ● Access to, and control of, a number of properties including position and size.
  • 17. window attributes and methods ● Attributes – document – name – Status ( the status line) – Parent ● Methods – Alert() – Close() – Prompt() – MoveTo() – MoveBy() – Open() – scroll() – ScrollTo() – resizeBy() – resizeTo()
  • 18. String Object ● A string is an immutable ordered sequence of 16-bit values, each of which represents a Unicode character - strings are JavaScript’s type for representing text. ● JavaScript does not have a special type that represents a single character of a string – To represent a single 16-bit value, we need to use a string that has a length of 1. ● Double-quote characters may be contained within strings delimited by single-quote characters, and single-quote characters may be contained within strings delimited by double quotes
  • 19. String Object ● "" // The empty string: it has zero characters; ● ' name="myform" ' ● "Wouldn't you prefer O'Reilly's book?" ● "This stringnhas two lines" ● "π = 3.14"
  • 20. Escape Sequences ● Backslash () is used to represent escape sequences ● xYY - The Latin-1 character rep by two hexadecimal digits XX ● uXXXX - The Unicode character specified by the four hexadecimal digits XXXX
  • 21. JavaScript escape sequences ● Sequence Character represented ● 0 The NUL character (u0000) ● b Backspace (u0008) ● t Horizontal tab (u0009) ● n Newline (u000A) ● v Vertical tab (u000B) ● f Form feed (u000C) ● r Carriage return (u000D) ● " Double quote (u0022) ● ' Apostrophe or single quote (u0027) ● Backslash (u005C)
  • 22. String Concatenation & String Length ● String Concatenation is supported by + operator ● msg = "Hello, " + "world"; // => "Hello, world" ● To determine the length of a string, the number of 16-bit values it contains, is retrieved using the length property of the string - s.length
  • 23. String Methods ● var s = "hello, world" ● s.charAt(0) ● s.charAt(s.length-1) ● s.substring(1,4) ● s.slice(1,4) ● s.slice(-3) ● s.indexOf("l") ● s.lastIndexOf("l") ● s.indexOf("l", 3) ● s.split(", ") ● s.replace("h", "H") ● s.toUpperCase() ● //Start with some text as example ● => "h": the first character. ● => "d": the last character. ● => "ell": chars 2, 3, and 4 ● => "ell": same thing ● => "rld": last 3 characters ● => 2: position of first l. ● => 10: position of last l. ● => 3: position at or after 3 ● => ["hello", "world"] ● => "Hello, world": ● replaces all instances ● => "HELLO, WORLD"
  • 24. Immutable Property of Strings ● Strings are immutable in JavaScript. ● Methods like replace() and toUpperCase() return new strings: they do not modify the string on which they are invoked. ● In ECMAScript 5, strings can be treated like read-only arrays, and we can access individual characters (16-bit values) from a string using square brackets instead of the charAt() method: ● s = "hello, world"; ● s[0] // => "h" ● s[s.length-1] // => "d"
  • 25. String to Numbers Conversion ● Global Functions – parseInt() ● parses only integers ● If a string begins with “0x” or “0X,” parseInt() interprets it as a hexadecimal number. ● It accepts an optional second argument specifying the radix (base) of the number to be parsed. (2 to 36) – parseFloat() - parses both integers and floating-point numbers. – Both functions skip leading whitespace, parse as many numeric characters as they can, and ignore anything that follows. – If the first nonspace character is not part of a valid numeric literal, they return NaN
  • 26. String to Numbers Conversion ● Examples – parseInt("3 blind mice") // => 3 – parseFloat(" 3.14 meters") // => 3.14 – parseInt("-12.34") // => -12 – parseInt("0xFF") // => 255 – parseFloat("$72.47"); // => NaN – parseInt("11", 2); // => 3 (1*2 + 1) – parseInt("077", 8); // => 63 (7*8 + 7) – parseInt("ff", 16); // => 255 (15*16 + 15)
  • 27. Number Conversion to String ● var n = 123456.789; ● n.toFixed(2); // "123456.79" ● n.toExponential(3); // "1.235e+5" ● n.toPrecision(7); // "123456.8"
  • 28. toString() ● The toString() method defined by the Number class accepts an optional argument that specifies a radix, or base, for the conversion. If not specified the conversion is done in base 10. ● Example – var n = 17; – binary_string = n.toString(2); // Evaluates to "10001" – octal_string = "0" + n.toString(8); // Evaluates to "021" – hex_string = "0x" + n.toString(16); // Evaluates to "0x11"
  • 29. Math Object ● JavaScript supports more complex mathematical operations through a set of functions and constants defined as properties of the Math object
  • 30. Math functions and Properties ● Math.pow(2,53) //=> 9007199254740992: 2 to the power 53 ● Math.round(.6) //=> 1.0: round to the nearest integer ● Math.ceil(.6) //=> 1.0: round up to an integer ● Math.floor(.6) //=> 0.0: round down to an integer ● Math.abs(-5) //=> 5: absolute value ● Math.max(x,y,z) //Return the largest argument ● Math.min(x,y,z) //Return the smallest argument ● Math.random() //Pseudo-random number 0 <= x < 1.0 ● Math.PI // π ● Math.E // e: The base of the natural logarithm
  • 31. Math functions and Properties ● Math.sqrt(3) // The square root of 3 ● Math.pow(3,1/3) // The cube root of 3 ● Math.sin(0) // Trig: also Math.cos, Math.atan, etc. ● Math.log(10) // Natural logarithm of 10 ● Math.log(100)/Math.LN10 // Base 10 logarithm of 100 ● Math.log(512)/Math.LN2 // Base 2 logarithm of 512 ● Math.exp(3) // Math.E cubed
  • 32. Infinity ● Arithmetic in JavaScript does not raise errors in cases of overflow, underflow, or division by zero. ● When the result of a numeric operation is larger than the largest representable number (overflow), the result is Infinity. ● Similarly, when a negative value becomes larger than the largest representable negative number, the result is negative infinity, printed as -Infinity. ● When adding, subtracting, multiplying, or dividing Infinity by anything results in an infinite value (possibly with the sign reversed).
  • 33. NaN ● The not-a-number value has a feature in JavaScript: it does not compare equal to any other value, including itself. ● x == NaN to determine whether the value of a variable x is NaN. Instead, you should write x != x, returns true if, and only if, x is NaN. ● The function – isNaN() - returns true if its argument is NaN, or if that argument is a nonnumeric value such as a string or an object. – isFinite() returns true if its argument is a number other than NaN, Infinity, or -Infinity
  • 34. Type Conversions ● Implicit Conversion – Boolean conversion as false for : ● undefined ● null ● 0 ● -0 ● NaN ● "" // the empty string – Boolean conversion to true - All other values, including all objects (and arrays)
  • 35. Type Conversions ● Implicit Conversion - Examples – 10 + " objects" // => "10 objects". 10 -> string – "7" * "4" // => 28: both strings -> numbers – var n = 1 – "x"; // => NaN: "x" can't convert to a number – n + " objects" // => "NaN objects": NaN -> "NaN" – Following comparisons are true, after conversion ● null == undefined //These two are treated as equal. ● "0" == 0 // String -> a number before comparing. ● 0 == false //Boolean -> number before comparing. ● "0" == false //Both operands -> 0 before comparing.
  • 36. Type Conversions ● Implicit Conversion ● If one operand of the + operator is a string, it converts the other one to a string. ● The unary + operator converts its operand to a number. ● And the unary ! operator converts its operand to a boolean and negates it. ● Examples – x + "" // Same as String(x) – +x // Same as Number(x). – x-0 // Same as Number(x). – !x // Same as Boolean(x)
  • 39. Type Conversions ● Explicit Conversion – done using the Boolean(), Number(), String(), or Object() functions: – Number("3") // => 3 – String(false) // => "false" Or false.toString() – Boolean([]) // => true – Object(3) // => new Number(3)
  • 40. Undeclared Variables ● Assigning a value to an undeclared variable, Java-Script actually creates that variable as a property of the global object, and it works like a properly declared global variable ● Best Practise – to declare the variables using 'var'
  • 41. Array Objects ● Arrays are supported as objects. ● Attribute length ● Methods include: concat, join, pop, push, reverse, sort
  • 42. EIW: Javascript the Language 42 Some similarity to C++ • Array indexes start at 0. • Syntax for accessing an element is the same: a[3]++; b[i] = i*72;
  • 43. EIW: Javascript the Language 43 New in JS • Arrays can grow dynamically – just add new elements at the end. • Arrays can have holes, elements that have no value. • Array elements can be anything – numbers, strings, or arrays!
  • 44. EIW: Javascript the Language 44 Creating Array Objects • With the new operator and a size: var x = new Array(10); • With the new operator and an initial set of element values: var y = new Array(18,”hi”,22); • Assignment of an array literal var x = [1,0,2];
  • 45. EIW: Javascript the Language 45 Arrays and Loops var a = new Array(4); for (i=0;i<a.length;i++) { a[i]=i; } for (j in a) { document.writeln(j); }
  • 46. EIW: Javascript the Language 46 Array Example var colors = [ “blue”, “green”, “yellow]; var x = window.prompt(“enter a number”); window.bgColor = colors[x];
  • 47. EIW: Javascript the Language 47 Array of Arrays • Javascript does not support 2-dimensional arrays (as part of the language). • BUT – each array element can be an array. • Resulting syntax looks like C++!
  • 48. EIW: Javascript the Language 48 Array of Arrays Example var board = [ [1,2,3], [4,5,6], [7,8,9] ]; for (i=0;i<3;i++) for (j=0;j<3;j++) board[i][j]++;