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

PDF
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
PPTX
Sources of research problem
Bhagwat Raut
 
PPTX
Neural networks.ppt
SrinivashR3
 
PPTX
AI PROJECT CYCLE.pptx
Jitendra Kumar Yadav
 
PDF
Class and Objects in Java
Spotle.ai
 
PPTX
Machine Learning Unit 1 Semester 3 MSc IT Part 2 Mumbai University
Madhav Mishra
 
PPTX
neural network
STUDENT
 
PPTX
Inheritance in OOPS
Ronak Chhajed
 
JavaScript - Chapter 8 - Objects
WebStackAcademy
 
Sources of research problem
Bhagwat Raut
 
Neural networks.ppt
SrinivashR3
 
AI PROJECT CYCLE.pptx
Jitendra Kumar Yadav
 
Class and Objects in Java
Spotle.ai
 
Machine Learning Unit 1 Semester 3 MSc IT Part 2 Mumbai University
Madhav Mishra
 
neural network
STUDENT
 
Inheritance in OOPS
Ronak Chhajed
 

What's hot (20)

PPT
Javascript arrays
Hassan Dar
 
PPT
JavaScript Objects
Reem Alattas
 
PDF
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
PPT
Introduction to Javascript
Amit Tyagi
 
PPT
Java Script ppt
Priya Goyal
 
PPTX
Java script
Shyam Khant
 
PDF
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
PPT
Jsp ppt
Vikas Jagtap
 
PPTX
Html forms
Er. Nawaraj Bhandari
 
PPSX
Javascript variables and datatypes
Varun C M
 
PDF
Javascript basics
shreesenthil
 
PPTX
Lab #2: Introduction to Javascript
Walid Ashraf
 
PPTX
Java script arrays
Frayosh Wadia
 
PDF
Methods in Java
Jussi Pohjolainen
 
PDF
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
PPT
9. Input Output in java
Nilesh Dalvi
 
PPT
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
PPTX
Bootstrap 5 ppt
Mallikarjuna G D
 
PPT
Js ppt
Rakhi Thota
 
PPTX
C# classes objects
Dr.Neeraj Kumar Pandey
 
Javascript arrays
Hassan Dar
 
JavaScript Objects
Reem Alattas
 
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Introduction to Javascript
Amit Tyagi
 
Java Script ppt
Priya Goyal
 
Java script
Shyam Khant
 
JavaScript - Chapter 12 - Document Object Model
WebStackAcademy
 
Jsp ppt
Vikas Jagtap
 
Javascript variables and datatypes
Varun C M
 
Javascript basics
shreesenthil
 
Lab #2: Introduction to Javascript
Walid Ashraf
 
Java script arrays
Frayosh Wadia
 
Methods in Java
Jussi Pohjolainen
 
JavaScript - Chapter 13 - Browser Object Model(BOM)
WebStackAcademy
 
9. Input Output in java
Nilesh Dalvi
 
Introduction to JavaScript (1).ppt
MuhammadRehan856177
 
Bootstrap 5 ppt
Mallikarjuna G D
 
Js ppt
Rakhi Thota
 
C# classes objects
Dr.Neeraj Kumar Pandey
 
Ad

Viewers also liked (20)

PPTX
Functions and Objects in JavaScript
Dhananjay Kumar
 
PPTX
JavaScript and OOP
easelsolutions
 
PDF
JavaScript DOM & event
Borey Lim
 
PDF
學習JavaScript_Dom
俊彬 李
 
PDF
Javascript, DOM, browsers and frameworks basics
Net7
 
PDF
JavaScript regular expression
Hernan Mammana
 
PPT
JavaScript & Dom Manipulation
Mohammed Arif
 
PPTX
Document Object Model
Mayur Mudgal
 
PPTX
Javascript validating form
Jesus Obenita Jr.
 
PPTX
Form Validation in JavaScript
Ravi Bhadauria
 
PPTX
Document object model(dom)
rahul kundu
 
PPT
DOM ( Document Object Model )
ITSTB
 
PDF
Javascript and DOM
Brian Moschel
 
PPTX
An Introduction to the DOM
Mindy McAdams
 
PDF
Let Search Power Your Intranet!
Ravi Mynampaty
 
PPTX
Javascript
Sun Technlogies
 
PPT
JavaScript Functions
Reem Alattas
 
PPTX
Introduction to Regular Expressions
Matt Casto
 
Functions and Objects in JavaScript
Dhananjay Kumar
 
JavaScript and OOP
easelsolutions
 
JavaScript DOM & event
Borey Lim
 
學習JavaScript_Dom
俊彬 李
 
Javascript, DOM, browsers and frameworks basics
Net7
 
JavaScript regular expression
Hernan Mammana
 
JavaScript & Dom Manipulation
Mohammed Arif
 
Document Object Model
Mayur Mudgal
 
Javascript validating form
Jesus Obenita Jr.
 
Form Validation in JavaScript
Ravi Bhadauria
 
Document object model(dom)
rahul kundu
 
DOM ( Document Object Model )
ITSTB
 
Javascript and DOM
Brian Moschel
 
An Introduction to the DOM
Mindy McAdams
 
Let Search Power Your Intranet!
Ravi Mynampaty
 
Javascript
Sun Technlogies
 
JavaScript Functions
Reem Alattas
 
Introduction to Regular Expressions
Matt Casto
 
Ad

Similar to javascript objects (20)

PDF
Programming in scala - 1
Mukesh Kumar
 
PDF
Scala for Java Developers
Martin Ockajak
 
PDF
JavaScript: Patterns, Part 2
Chris Farrell
 
PPTX
JavaScript.pptx
KennyPratheepKumar
 
PDF
8 introduction to_java_script
Vijay Kalyan
 
ODP
Introduction To Scala
Basuk
 
PDF
Javascript
20261A05H0SRIKAKULAS
 
PPTX
Java script
Adrian Caetano
 
PDF
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
An Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Scala.pdf
ssuser155dbc1
 
PDF
9.4json
Andrew Dunstan
 
PPT
An introduction to javascript
MD Sayem Ahmed
 
PDF
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
PDF
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
PPTX
Javascript analysis
Uchitha Bandara
 
PPT
Java Script Introduction
jason hu 金良胡
 
PDF
Ruby training day1
Bindesh Vijayan
 
PDF
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
PDF
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 
Programming in scala - 1
Mukesh Kumar
 
Scala for Java Developers
Martin Ockajak
 
JavaScript: Patterns, Part 2
Chris Farrell
 
JavaScript.pptx
KennyPratheepKumar
 
8 introduction to_java_script
Vijay Kalyan
 
Introduction To Scala
Basuk
 
Java script
Adrian Caetano
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala.pdf
ssuser155dbc1
 
An introduction to javascript
MD Sayem Ahmed
 
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Javascript analysis
Uchitha Bandara
 
Java Script Introduction
jason hu 金良胡
 
Ruby training day1
Bindesh Vijayan
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 

Recently uploaded (20)

PPTX
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
PDF
Brief History of Internet - Early Days of Internet
sutharharshit158
 
PPTX
Coupa-Overview _Assumptions presentation
annapureddyn
 
PDF
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
PDF
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
PDF
Software Development Methodologies in 2025
KodekX
 
PPTX
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
PDF
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
PDF
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
PDF
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
PDF
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
PDF
This slide provides an overview Technology
mineshkharadi333
 
PPTX
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
PPTX
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
PDF
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
PDF
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
PDF
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
PDF
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
PDF
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
PPTX
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 
AI and Robotics for Human Well-being.pptx
JAYMIN SUTHAR
 
Brief History of Internet - Early Days of Internet
sutharharshit158
 
Coupa-Overview _Assumptions presentation
annapureddyn
 
Event Presentation Google Cloud Next Extended 2025
minhtrietgect
 
MASTERDECK GRAPHSUMMIT SYDNEY (Public).pdf
Neo4j
 
Software Development Methodologies in 2025
KodekX
 
IoT Sensor Integration 2025 Powering Smart Tech and Industrial Automation.pptx
Rejig Digital
 
Research-Fundamentals-and-Topic-Development.pdf
ayesha butalia
 
Data_Analytics_vs_Data_Science_vs_BI_by_CA_Suvidha_Chaplot.pdf
CA Suvidha Chaplot
 
BLW VOCATIONAL TRAINING SUMMER INTERNSHIP REPORT
codernjn73
 
Cloud-Migration-Best-Practices-A-Practical-Guide-to-AWS-Azure-and-Google-Clou...
Artjoker Software Development Company
 
This slide provides an overview Technology
mineshkharadi333
 
The-Ethical-Hackers-Imperative-Safeguarding-the-Digital-Frontier.pptx
sujalchauhan1305
 
How to Build a Scalable Micro-Investing Platform in 2025 - A Founder’s Guide ...
Third Rock Techkno
 
AI Unleashed - Shaping the Future -Starting Today - AIOUG Yatra 2025 - For Co...
Sandesh Rao
 
Trying to figure out MCP by actually building an app from scratch with open s...
Julien SIMON
 
Tea4chat - another LLM Project by Kerem Atam
a0m0rajab1
 
Presentation about Hardware and Software in Computer
snehamodhawadiya
 
How Open Source Changed My Career by abdelrahman ismail
a0m0rajab1
 
ChatGPT's Deck on The Enduring Legacy of Fax Machines
Greg Swan
 

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]++;