Thursday, 19 March 2020

JavaScript Objects

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

primitive value is a value that has no properties or methods.
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).

Object Methods

Methods are actions that can be performed on objects.
Object properties can be both primitive values, other objects, and functions.
An object method is an object property containing a function definition.
PropertyValue
firstNameJohn
lastNameDoe
age50
eyeColorblue
fullNamefunction() {return this.firstName + " " + this.lastName;}
JavaScript objects are containers for named values, called properties and methods.


Creating a JavaScript Object

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.
In ECMAScript 5, an object can also be created with the function Object.create().

var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"};

With new keyword

var person = new Object();
person.firstName = "John";
person.lastName = "Doe";
person.age = 50;
person.eyeColor = "blue";


objectName.property         // person.age
objectName["property"]      // person["age"]
objectName[expression]      // x = "age"; person[x]
భరద్వాజ 

shortest FizBuzz Javascipt