HTML5 APPLICATIONS DEVELOPMENT MANUAL (2016)
22 - Objects in JavaScript
An HTML element is an object, like a house or a car. Just as with real life objects, we can access and modify HTML objects that appear on a screen.
The creation of interactive Web pages and apps relies on our ability to manipulate objects on a screen. Objects are models of things in the real world that were built using data. Objects are grouped into object models, which are used to represent Browsers and Web pages.
In JavaScript, almost "everything" is an object.
- Booleans can be objects (if defined with the new keyword)
- Numbers can be objects (if defined with the new keyword)
- Strings can be objects (if defined with the new keyword)
- Dates are always objects
- Maths are always objects
- Regular expressions are always objects
- Arrays are always objects
- Functions are always objects
- Objects are always objects
All JavaScript values, except primitives, are objects.
JavaScript Primitives
A primitive value is a value that has no properties or methods.
A primitive data type is data that has a primitive value.
JavaScript defines 5 types of primitive data types:
- string
- number
- boolean
- null
- undefined
Primitive values are immutable (they are hardcoded and therefore cannot be changed).
Value |
Type |
Comment |
"Hello" |
string |
"Hello" is always "Hello" |
mar.14 |
number |
3.14 is always 3.14 |
TRUE |
boolean |
true is always true |
FALSE |
boolean |
false is always false |
null |
null (object) |
null is always null |
undefined |
undefined |
undefined is always undefined |
With JavaScript, you can define and create your own objects.
There are different ways to create new objects:
- Define and create a single object, using an object literal.
- Define and create a single object, with the keyword new.
- Define an object constructor, and then create objects of the constructed type.
<!DOCTYPE html>
<html>
<head>
<title></title>
</head>
<body>
<p>Creating a JavaScript Object.</p>
<p id="demo"></p>
<script>
var person = {
firstName: "John",
lastName: "Doe",
age: 50,
eyeColor: "blue"
};
document.getElementById("demo").innerHTML =
person.firstName + " " + person.lastName;
</script>
</body>
</html>