SlideShare ist ein Scribd-Unternehmen logo
1 von 48
Downloaden Sie, um offline zu lesen
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)
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]++;

Weitere ähnliche Inhalte

Was ist angesagt?

Was ist angesagt? (20)

Javascript 101
Javascript 101Javascript 101
Javascript 101
 
Javascript arrays
Javascript arraysJavascript arrays
Javascript arrays
 
Functions in javascript
Functions in javascriptFunctions in javascript
Functions in javascript
 
Dom(document object model)
Dom(document object model)Dom(document object model)
Dom(document object model)
 
JavaScript - Chapter 12 - Document Object Model
  JavaScript - Chapter 12 - Document Object Model  JavaScript - Chapter 12 - Document Object Model
JavaScript - Chapter 12 - Document Object Model
 
JavaScript - Chapter 4 - Types and Statements
 JavaScript - Chapter 4 - Types and Statements JavaScript - Chapter 4 - Types and Statements
JavaScript - Chapter 4 - Types and Statements
 
JavaScript Objects
JavaScript ObjectsJavaScript Objects
JavaScript Objects
 
javaScript.ppt
javaScript.pptjavaScript.ppt
javaScript.ppt
 
Form Validation in JavaScript
Form Validation in JavaScriptForm Validation in JavaScript
Form Validation in JavaScript
 
Js ppt
Js pptJs ppt
Js ppt
 
JavaScript - Chapter 10 - Strings and Arrays
 JavaScript - Chapter 10 - Strings and Arrays JavaScript - Chapter 10 - Strings and Arrays
JavaScript - Chapter 10 - Strings and Arrays
 
jQuery
jQueryjQuery
jQuery
 
Javascript validating form
Javascript validating formJavascript validating form
Javascript validating form
 
PHP Loops and PHP Forms
PHP  Loops and PHP FormsPHP  Loops and PHP Forms
PHP Loops and PHP Forms
 
Asp.NET Validation controls
Asp.NET Validation controlsAsp.NET Validation controls
Asp.NET Validation controls
 
jQuery
jQueryjQuery
jQuery
 
Introduction of Html/css/js
Introduction of Html/css/jsIntroduction of Html/css/js
Introduction of Html/css/js
 
Javascript basics
Javascript basicsJavascript basics
Javascript basics
 
cascading style sheet ppt
cascading style sheet pptcascading style sheet ppt
cascading style sheet ppt
 
Javascript event handler
Javascript event handlerJavascript event handler
Javascript event handler
 

Andere mochten auch

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 & eventBorey 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 basicsNet7
 
JavaScript regular expression
JavaScript regular expressionJavaScript regular expression
JavaScript regular expressionHernan Mammana
 
Document Object Model
Document Object ModelDocument Object Model
Document Object ModelMayur Mudgal
 
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 DOMMindy 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 ExpressionsMatt Casto
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Modelchomas kandar
 

Andere mochten auch (19)

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
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
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
 
JavaScript Functions
JavaScript Functions JavaScript Functions
JavaScript Functions
 
Introduction to Regular Expressions
Introduction to Regular ExpressionsIntroduction to Regular Expressions
Introduction to Regular Expressions
 
Regular Expressions
Regular ExpressionsRegular Expressions
Regular Expressions
 
Document Object Model
Document Object ModelDocument Object Model
Document Object Model
 
Seo tools - on page
Seo tools - on pageSeo tools - on page
Seo tools - on page
 

Ähnlich wie JavaScript Objects, Methods and Math Guide

Programming in scala - 1
Programming in scala - 1Programming in scala - 1
Programming in scala - 1Mukesh Kumar
 
Scala for Java Developers
Scala for Java DevelopersScala for Java Developers
Scala for Java DevelopersMartin Ockajak
 
JavaScript: Patterns, Part 2
JavaScript: Patterns, Part  2JavaScript: Patterns, Part  2
JavaScript: Patterns, Part 2Chris Farrell
 
8 introduction to_java_script
8 introduction to_java_script8 introduction to_java_script
8 introduction to_java_scriptVijay Kalyan
 
Introduction To Scala
Introduction To ScalaIntroduction To Scala
Introduction To ScalaBasuk
 
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 DevelopersMiles 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 DevelopersMiles Sabin
 
An introduction to javascript
An introduction to javascriptAn introduction to javascript
An introduction to javascriptMD 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 DevelopersMiles 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 DevelopersSkills Matter
 
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 | CloudxLabCloudxLab
 
Quick python reference
Quick python referenceQuick python reference
Quick python referenceJayant Parida
 

Ähnlich wie JavaScript Objects, Methods and Math Guide (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
 
Quick python reference
Quick python referenceQuick python reference
Quick python reference
 

Kürzlich hochgeladen

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreternaman860154
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking MenDelhi Call girls
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...Neo4j
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Scriptwesley chun
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessPixlogix Infotech
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationMichael W. Hawkins
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsJoaquim Jorge
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024The Digital Insurer
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfsudhanshuwaghmare1
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Drew Madelung
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Igalia
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Enterprise Knowledge
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsMaria Levchenko
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptxHampshireHUG
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024The Digital Insurer
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CVKhem
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdfhans926745
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?Antenna Manufacturer Coco
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEarley Information Science
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationRadu Cotescu
 

Kürzlich hochgeladen (20)

Presentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreterPresentation on how to chat with PDF using ChatGPT code interpreter
Presentation on how to chat with PDF using ChatGPT code interpreter
 
08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men08448380779 Call Girls In Civil Lines Women Seeking Men
08448380779 Call Girls In Civil Lines Women Seeking Men
 
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...Workshop - Best of Both Worlds_ Combine  KG and Vector search for  enhanced R...
Workshop - Best of Both Worlds_ Combine KG and Vector search for enhanced R...
 
Automating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps ScriptAutomating Google Workspace (GWS) & more with Apps Script
Automating Google Workspace (GWS) & more with Apps Script
 
Advantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your BusinessAdvantages of Hiring UIUX Design Service Providers for Your Business
Advantages of Hiring UIUX Design Service Providers for Your Business
 
GenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day PresentationGenCyber Cyber Security Day Presentation
GenCyber Cyber Security Day Presentation
 
Artificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and MythsArtificial Intelligence: Facts and Myths
Artificial Intelligence: Facts and Myths
 
Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024Axa Assurance Maroc - Insurer Innovation Award 2024
Axa Assurance Maroc - Insurer Innovation Award 2024
 
Boost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdfBoost Fertility New Invention Ups Success Rates.pdf
Boost Fertility New Invention Ups Success Rates.pdf
 
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
Strategies for Unlocking Knowledge Management in Microsoft 365 in the Copilot...
 
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
Raspberry Pi 5: Challenges and Solutions in Bringing up an OpenGL/Vulkan Driv...
 
Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...Driving Behavioral Change for Information Management through Data-Driven Gree...
Driving Behavioral Change for Information Management through Data-Driven Gree...
 
Handwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed textsHandwritten Text Recognition for manuscripts and early printed texts
Handwritten Text Recognition for manuscripts and early printed texts
 
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
04-2024-HHUG-Sales-and-Marketing-Alignment.pptx
 
Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024Finology Group – Insurtech Innovation Award 2024
Finology Group – Insurtech Innovation Award 2024
 
Real Time Object Detection Using Open CV
Real Time Object Detection Using Open CVReal Time Object Detection Using Open CV
Real Time Object Detection Using Open CV
 
[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf[2024]Digital Global Overview Report 2024 Meltwater.pdf
[2024]Digital Global Overview Report 2024 Meltwater.pdf
 
What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?What Are The Drone Anti-jamming Systems Technology?
What Are The Drone Anti-jamming Systems Technology?
 
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptxEIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
EIS-Webinar-Prompt-Knowledge-Eng-2024-04-08.pptx
 
Scaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organizationScaling API-first – The story of a global engineering organization
Scaling API-first – The story of a global engineering organization
 

JavaScript Objects, Methods and Math Guide

  • 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)
  • 37.
  • 38.
  • 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]++;