JavaScript Object Definitions

JavaScript has several built-in objects such as Number, Array, String, Date, and Math.

Each of these built-in objects has member properties and methods.

In addition to the JavaScript objects, Node.js, MongoDB, Express, and Angular add their own built-in objects as well.

JavaScript provides a nice object-oriented programming structure for you to create your own custom objects.

Using objects rather than just a collection of functions is key to writing clean, efficient, reusable JavaScript code.

An object is really just a container to group multiple values and, in some instances, functions together.

The values of an object are called properties, and functions are called methods.

Number Object

For example, to create a number object, you use the following line of code to create an instance of the built-in Number object in JavaScript:


let x = new Number("5");

Or you can do it literary.


let y = 10;

Example


let x = new Number("5");
let y = 10;

console.log(x);
console.log(y);

Creating Custom-Defined Objects

Using the built-in JavaScript objects has several advantages

JavaScript objects can be defined in a couple different ways.

Method-1: Fly method

You create a generic object and then add properties to it as needed. For example, to create a user object and assign a first and last name as well as define a function to return the name, you could use the following code:


let user = new Object();
  user.firstName = "Bilal";
  user.lastName = "Mubarak";
  user.getName = function() {
    return this.firstName + " " + this.firstName;
}

Method-2

To accomplish the same thing through direct assignment using the following syntax where the object is enclosed in {} and the properties are defined using property:value syntax:


let user = {
  firstName:"Bilal",
  lastName:"Idris"
  getName:function(){ 
    return this.firstName + " " + this.firstName;
  }
};

            

Method-3

A better method for reusable objects is to actually enclose the object inside its own function block.

This has the advantage of allowing you to keep all the code pertaining to the object local to the object itself. For example:


function User(firstName, lastName) {
  this.firstName = firstName,
  this.lastName = lastName,
  this.getName:function(){ 
    return this.firstName + " " + this.lastName;
  }
};

let user = new User("Ahmad", "Bello");
console.log(user.getName());

            

Example


function User(firstName, lastName) {
  this.firstName = firstName,
  this.lastName = lastName,
  this.getName:function(){ 
    return this.firstName + " " + this.lastName;
  }
};

let user = new User("Ahmad", "Bello");
console.log(user.getName());

Using a Prototyping Object Pattern

The prototyping pattern is implemented by defining the functions inside the prototype attribute of the object instead of the object itself.


function User(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

User.prototype.getName = function(){ 
    return this.firstName + " " + this.lastName;
};
            

Example


function User(firstName, lastName) {
  this.firstName = firstName;
  this.lastName = lastName;
}

User.prototype.getName = function(){ 
  return this.firstName + " " + this.lastName;
};

let user = new User("Ahmad", "Bello");
console.log(user.getName());

Manipulating Strings

The String object is by far the most commonly used object in JavaScript.

JavaScript automatically creates a String object for you any time you define a variable that has a string data type.

For example:


let myString = "Teach Yourself jQuery & JavaScript in 24 Hours";
            

Or using other way


let b = new String("this is another way of creating string");
            

Example


let myString = "Teach Yourself jQuery & JavaScript in 24 Hours";
let b = new String("this is another way of creating string");

console.log(myString);
console.log(b);

String object escape codes

Escape Description Example Output
\' Single quot mark "Couldn\'t be" Couldn't be
\" Double quot mark "I \"think\" \"am\" " I "think" "am"
\\ Backslash "One\\Two\\Three" One\Two\Three
\n New line "I am\n I said" I am
I said"
\r Carriage return "To be\ror not" To be or not
\t Tab "One\tTwo\tThree" One Two Three
\b Backspace "Correction\b\b\bion" Correction
\f Form feed "Title A\f Title B" Title A then
Title B

Method to manipulate String object

Method Description
chatAt(index) Returns the character at the specified index
chartCodeAt(index) Returns the unicode value of the character at the specified index
concat(str1, str2, ...) Joins two or more strings, and returns a copy of the joined string
fromCharCode() Converts unicode values to actual characters
indexOf(subString) Returns the position of the first occurrence of a specified subString value. Returns -1 if the substring is not found
lastIndexOf(subString) Returns the position of the last occurrence of a specified subString value. Returns -1 if the substring is not found
match(regex) Searches the string and returns all matches to regular expression
replace(subString/regex, replacementString) Searches the string for match of the subString or regular expression and replaces the matched substring with a new substring
search(regex) Searches the string based on the regular expression and returns the position of the first match
slice(start, end) Returns a new string that has the position of the string between the start and end positions removed
split(sep, limit) Split a string into an array of substrings based on a separator character or regular expression. The optioal between limit argument defines the maximum number of splits to make starting from the beginnning
substr(start, length) Extracts the characters from a string, beginnning at a specified start position and through the specified length of characters
substring(from, to) Returns a substring of characters between the from and to index
toLowerCase() Converts the string to lowercase
toUpperCase() Converts the string to uppercase
valueOf() Returns the primitive string value

Searching a String for a Substring

Here is an example of how to search a substring withing the sentence.


let myString = "I think, therefore I am.";

if (myString.indexOf("think") != -1 ){ 
  console.log(myString);
}

Example


let myString = "I think, therefore I am.";

if (myString.indexOf("think") != -1 ){ 
  console.log(myString);
}

Replacing a Word in a String

Here is an example of how to replace a word withing the string.


let username = "Adam";
let output = "<username>please enter your password:";

output.replace("<username>", username)

console.log(output);

Example


let username = "Adam";
let output = "<username>please enter your password:";

output = output.replace("<username>", username)

console.log(output);

Splitting a String into an Array

Here is an example of how to split a string to an array.


let time = "12:10:36";
let newTime = time.split(":");

let hout = newTime[0]; // 12
let minute = newTime[1]; // 10
let second = newTime[2]; // 36

Example


let time = "12:10:36";
let newTime = time.split(":");

let hout = newTime[0]; // 12
let minute = newTime[1]; // 10
let second = newTime[2]; // 36

console.log(hout);
console.log(minute);
console.log(second);

This is the object literal syntax, which is one of the nicest things in JavaScript.

You can also use the new Objectsyntax:


const car = new Object();

Another syntax is to use Object.create():


const car = Object.create();

You can also initialize an object using the newkeyword before a function with a capital letter. This function serves as a constructor for that object. In there, we can initialize the arguments we receive as parameters, to set up the initial state of the object:


function Car(brand, model) {
  this.brand = brand
  this.model = model
};

We initialize a new object using


const myCar = new Car("Ford", "Fiesta") {
  myCar.brand//'Ford'
  myCar.model//'Fiesta'

Objects are always passed by reference.

If you assign a variable the same value of another, if it's a primitive type like a number or a string, they are passed by value:

Take this example:


let age = 36;
let myAge = age;
myAge = 37;
age //36


let car = {
  color:"blue"
};
let anotherCar = age;
anotherCar.color = "yellow"
car.color //"yellow"