(Go: >> BACK << -|- >> HOME <<)

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

Css selectors
Css selectorsCss selectors
Css selectors
Parth Trivedi
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
Taha Malampatti
 
Ajax
AjaxAjax
Ajax
Tech_MX
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
Alaref Abushaala
 
Php mysql ppt
Php mysql pptPhp mysql ppt
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
TheCreativedev Blog
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
Bala Narayanan
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
Varun C M
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
WebStackAcademy
 
Javascript
JavascriptJavascript
Javascript
Manav Prasad
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
Andres Baravalle
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
Amit Tyagi
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
Maitree Patel
 
Java script
Java scriptJava script
Java script
Abhishek Kesharwani
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
Partnered Health
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
Rajat Saxena
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
WebStackAcademy
 
Java script
Java scriptJava script
Java script
Shyam Khant
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
Forziatech
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
Manvendra Singh
 

What's hot (20)

Css selectors
Css selectorsCss selectors
Css selectors
 
Introduction to php
Introduction to phpIntroduction to php
Introduction to php
 
Ajax
AjaxAjax
Ajax
 
Javascript functions
Javascript functionsJavascript functions
Javascript functions
 
Php mysql ppt
Php mysql pptPhp mysql ppt
Php mysql ppt
 
PHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and requirePHP - DataType,Variable,Constant,Operators,Array,Include and require
PHP - DataType,Variable,Constant,Operators,Array,Include and require
 
Basics of JavaScript
Basics of JavaScriptBasics of JavaScript
Basics of JavaScript
 
Javascript variables and datatypes
Javascript variables and datatypesJavascript variables and datatypes
Javascript variables and datatypes
 
JavaScript - Chapter 11 - Events
 JavaScript - Chapter 11 - Events  JavaScript - Chapter 11 - Events
JavaScript - Chapter 11 - Events
 
Javascript
JavascriptJavascript
Javascript
 
Introduction to JavaScript
Introduction to JavaScriptIntroduction to JavaScript
Introduction to JavaScript
 
Introduction to Javascript
Introduction to JavascriptIntroduction to Javascript
Introduction to Javascript
 
Form using html and java script validation
Form using html and java script validationForm using html and java script validation
Form using html and java script validation
 
Java script
Java scriptJava script
Java script
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
Datatype in JavaScript
Datatype in JavaScriptDatatype in JavaScript
Datatype in JavaScript
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
Java script
Java scriptJava script
Java script
 
Object Oriented Programming In JavaScript
Object Oriented Programming In JavaScriptObject Oriented Programming In JavaScript
Object Oriented Programming In JavaScript
 
JavaScript - An Introduction
JavaScript - An IntroductionJavaScript - An Introduction
JavaScript - An Introduction
 

Viewers also liked

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
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
 
Functions in javascript
Functions in javascriptFunctions in javascript
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
 

Viewers also liked (20)

Functions and Objects in JavaScript
Functions and Objects in JavaScript Functions and Objects in JavaScript
Functions and Objects in JavaScript
 
JavaScript and OOP
JavaScript and OOPJavaScript and OOP
JavaScript and OOP
 
JavaScript DOM & event
JavaScript DOM & eventJavaScript DOM & event
JavaScript DOM & event
 
學習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
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
JavaScript regular expression
JavaScript regular expressionJavaScript regular expression
JavaScript regular expression
 
JavaScript & Dom Manipulation
JavaScript & Dom ManipulationJavaScript & Dom Manipulation
JavaScript & Dom Manipulation
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Document object model(dom)
Document object model(dom)Document object model(dom)
Document object model(dom)
 
DOM ( Document Object Model )
DOM ( Document Object Model )DOM ( Document Object Model )
DOM ( Document Object Model )
 
Javascript and DOM
Javascript and DOMJavascript and DOM
Javascript and DOM
 
An Introduction to the DOM
An Introduction to the DOMAn Introduction to the DOM
An Introduction to the DOM
 
Let Search Power Your Intranet!
Let Search Power Your Intranet!Let Search Power Your Intranet!
Let Search Power Your Intranet!
 
Javascript
JavascriptJavascript
Javascript
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Introduction to Regular Expressions
Introduction to Regular ExpressionsIntroduction to Regular Expressions
Introduction to Regular Expressions
 

Similar to javascript objects

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
Mukesh Kumar
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
Martin Ockajak
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
Chris Farrell
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
KennyPratheepKumar
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
Vijay Kalyan
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
Basuk
 
Javascript
JavascriptJavascript
Java script
Java scriptJava script
Java script
Adrian Caetano
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
Miles Sabin
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
Miles Sabin
 
Scala.pdf
Scala.pdfScala.pdf
Scala.pdf
ssuser155dbc1
 
9.4json
9.4json9.4json
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
MD Sayem Ahmed
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
Miles Sabin
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
Skills Matter
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
Uchitha Bandara
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
jason hu 金良胡
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
Bindesh Vijayan
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
CloudxLab
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
WebStackAcademy
 

Similar to javascript objects (20)

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java Developers
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2
 
JavaScript.pptx
JavaScript.pptxJavaScript.pptx
JavaScript.pptx
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_script
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To Scala
 
Javascript
JavascriptJavascript
Javascript
 
Java script
Java scriptJava script
Java script
 
BCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java DevelopersBCS SPA 2010 - An Introduction to Scala for Java Developers
BCS SPA 2010 - An Introduction to Scala for Java Developers
 
An Introduction to Scala for Java Developers
An Introduction to Scala for Java DevelopersAn Introduction to Scala for Java Developers
An Introduction to Scala for Java Developers
 
Scala.pdf
Scala.pdfScala.pdf
Scala.pdf
 
9.4json
9.4json9.4json
9.4json
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascript
 
A Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java DevelopersA Brief Introduction to Scala for Java Developers
A Brief Introduction to Scala for Java Developers
 
Miles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java DevelopersMiles Sabin Introduction To Scala For Java Developers
Miles Sabin Introduction To Scala For Java Developers
 
Javascript analysis
Javascript analysisJavascript analysis
Javascript analysis
 
Java Script Introduction
Java Script IntroductionJava Script Introduction
Java Script Introduction
 
Ruby training day1
Ruby training day1Ruby training day1
Ruby training day1
 
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLabIntroduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
Introduction to Scala | Big Data Hadoop Spark Tutorial | CloudxLab
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 

Recently uploaded

LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
SelfMade bd
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
Google Developer Group - Harare
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
Priyanka Aash
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
siddu769252
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
Baishakhi Ray
 
How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...
DianaGray10
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
KIRAN KV
 
Discovery Series - Zero to Hero - Task Mining Session 1
Discovery Series - Zero to Hero - Task Mining Session 1Discovery Series - Zero to Hero - Task Mining Session 1
Discovery Series - Zero to Hero - Task Mining Session 1
DianaGray10
 
Zaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdfZaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdf
AmandaCheung15
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
sunilverma7884
 
Keynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive SecurityKeynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive Security
Priyanka Aash
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
ZachWylie3
 
Improving Learning Content Efficiency with Reusable Learning Content
Improving Learning Content Efficiency with Reusable Learning ContentImproving Learning Content Efficiency with Reusable Learning Content
Improving Learning Content Efficiency with Reusable Learning Content
Enterprise Knowledge
 
Retrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with RagasRetrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with Ragas
Zilliz
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
Tech Guru
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
Steven Carlson
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
Zilliz
 
NVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space ExplorationNVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space Exploration
Alison B. Lowndes
 
Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17
Bhajan Mehta
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
FIDO Alliance
 

Recently uploaded (20)

LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdfLeadMagnet IQ Review:  Unlock the Secret to Effortless Traffic and Leads.pdf
LeadMagnet IQ Review: Unlock the Secret to Effortless Traffic and Leads.pdf
 
Google I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged SlidesGoogle I/O Extended Harare Merged Slides
Google I/O Extended Harare Merged Slides
 
Finetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and DefendingFinetuning GenAI For Hacking and Defending
Finetuning GenAI For Hacking and Defending
 
Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024Generative AI Reasoning Tech Talk - July 2024
Generative AI Reasoning Tech Talk - July 2024
 
Semantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software DevelopmentSemantic-Aware Code Model: Elevating the Future of Software Development
Semantic-Aware Code Model: Elevating the Future of Software Development
 
How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...How UiPath Discovery Suite supports identification of Agentic Process Automat...
How UiPath Discovery Suite supports identification of Agentic Process Automat...
 
kk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdfkk vathada _digital transformation frameworks_2024.pdf
kk vathada _digital transformation frameworks_2024.pdf
 
Discovery Series - Zero to Hero - Task Mining Session 1
Discovery Series - Zero to Hero - Task Mining Session 1Discovery Series - Zero to Hero - Task Mining Session 1
Discovery Series - Zero to Hero - Task Mining Session 1
 
Zaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdfZaitechno Handheld Raman Spectrometer.pdf
Zaitechno Handheld Raman Spectrometer.pdf
 
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
Girls call Kolkata 👀 XXXXXXXXXXX 👀 Rs.9.5 K Cash Payment With Room Delivery
 
Keynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive SecurityKeynote : AI & Future Of Offensive Security
Keynote : AI & Future Of Offensive Security
 
Camunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptxCamunda Chapter NY Meetup July 2024.pptx
Camunda Chapter NY Meetup July 2024.pptx
 
Improving Learning Content Efficiency with Reusable Learning Content
Improving Learning Content Efficiency with Reusable Learning ContentImproving Learning Content Efficiency with Reusable Learning Content
Improving Learning Content Efficiency with Reusable Learning Content
 
Retrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with RagasRetrieval Augmented Generation Evaluation with Ragas
Retrieval Augmented Generation Evaluation with Ragas
 
Intel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdfIntel Unveils Core Ultra 200V Lunar chip .pdf
Intel Unveils Core Ultra 200V Lunar chip .pdf
 
Vulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive OverviewVulnerability Management: A Comprehensive Overview
Vulnerability Management: A Comprehensive Overview
 
The History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal EmbeddingsThe History of Embeddings & Multimodal Embeddings
The History of Embeddings & Multimodal Embeddings
 
NVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space ExplorationNVIDIA at Breakthrough Discuss for Space Exploration
NVIDIA at Breakthrough Discuss for Space Exploration
 
Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17Mule Experience Hub and Release Channel with Java 17
Mule Experience Hub and Release Channel with Java 17
 
UX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business GoalsUX Webinar Series: Aligning Authentication Experiences with Business Goals
UX Webinar Series: Aligning Authentication Experiences with Business Goals
 

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