Solve Real-world Problems with JavaScript Objects, Methods and Properties

Solve Real-world Problems with JavaScript Objects, Methods and Properties

You might suspect that how JavaScript correspond to real world problems and the answer lies in objects, methods and properties, they help us solve real-world problems. Let’s assume a person as an object which can see, hear, eat and walk etc. we call them function / methods of an object. How far the person can see, how loud can hear and how much can eat, properties define for an object. As an example, a child eats less than an adult, so defining properties for each object will help us differentiate between objects. We will take a quick look how we create and use objects, their methods and properties.

Most common objects / reference data-types built-in to JavaScript are Arrays, Date, Math and String. The basic purpose of an object is to not just create a data container but facilitate with methods and properties to do additional work on the data depending on requirement of the purpose. They give you flexibility to mimik real-world objects in programming using reference data-types.

Realworld objects

This how you can create an object in JavaScript:

//Creating an object of array
 var myArray = new Array();

You can also assign one object to another by referencing the memory-address of object on right to left-side of the object. Here’s how you can do it:

//Assigning one object another 
var myArray1 = new Array(1, 2, 3, 4, 5); 
var myArray2 = myArray1;

Now you got a general perception about objects, methods and properties. Next question comes into mind after creating objects how we access methods and properties of a new object. Before that let’s answer these in your mind:

1. Define characteristics of an object with Properties and apply your desired operation with its Methods

Primitive Types Vs. Objects Primitive types are standard data-types that are lightweight to hold your data without offering any additional methods or properties. However, a data-type as an object or reference-type offers a lot of flexibilities by providing methods and properties belongs to its reference data-type.

var myString = new String("I’m a String object"); 

//object or reference-type 
var myString = "This is primitive string";

//primitive-type 
var stringLength = myString.length;  

//string concatenation not summation  
theResult = "12" + 2323; 

Trying Object’s properties from primitive data will temporary make primitive data into object, after accessing method or properties object temporarily created will be destroyed.

2. How to Declare/Initialize a Built-in Object in JavaScript?

Let’s take an example of declaring an object and using its method and properties to give you a quick look of an object capabilities. Initially, you need to know about constructor of your object written in class definition and parameters to pass (like in general how much person would eat 2 eggs, 4 breads, etc. they are parameters when defined and arguments when passed to the function when calling the function):

//Creating and initializing an object 
var myVariable = new ConstructorName(optional parameters);

//Using object's properties. Second line modifies an object’s property 
var totalElements = myArray.length; 
myArray.length = 12;

//Calling an object's method, a pair of parenthesis is necessary 
myArray.sort()

Note: Read-only properties can’t be changed…

a. Object’s Properties:

Properties helps to set and modify the characteristic of an object so to differente among other objects. You can access any reference variable’s properties by using variable name and a dot operator “.” after its name. For example, the length property below will return total number elements in the array:

myArray.length;

b. Object’s Method or Function:

Sometimes you need to perform some set of actions a on a variable or an object. For example, booking an order, delivering a mail packet, organizing your files in order, submitting information, and etc. Below is a way to calling a function, this is an array method that sort its contents:

myArray.sort();

3. Writing your Own Function

Now what if you need to write a function for choosing a person from a group who age is greater than 45. This is how you would write a function in JavaScript:

//Sample function
function functionName(parameter List,)
{
	//your statements
}

//Writing a function
function chooseLeader(people,index) //function header
{
 var choice = -1;
 
//looking for desired person 
 for(index in people) { 
     if(people[index] > 45) { 
         console.log("leader is found"); 
         choice = index break; 
         } 
  }

//when loop fail to find one 
 if(choice == -1) { 
	 console.log("Leader not found"); }
	return choice;
}

//Using the function in action
var people = new Array(45, 33, 56, 77);

var leaderIndex = chooseLeader(people, 0); 
chooseLeader(people,0);  //function call

SayHelloMe(); Did you know? What’s missing for SayHelloMe()? the missing part is its function header and defintion. In other case, function call for SayHelloMe won’t work. Scope: Where is variable available to you in which range of lines. This simply explains the concept of scope. Variable global or page-level scope. It’s a bad practice to assign a variable within function…

Lifetime: How long and where variable is retained in the program is its ‘lifetime’. A variable declared within function will remain within function, it will available to memory only when function is called once function execution completes variable will no longer be available to memory…

Here are some other methods and properties of String object in JavaScript. You will see more later…

String Method & Properties What method does it for you?

String Function Task
String.length Returns number of element in a string object
indexOf() Returns first index number of string passed to method e.g. String.indexOf("Hello")
lastIndexOf() Locate for last occurrence of your string and returns its first index number
substring() A good way to cut a string and assign to another string
replace("search","replace") Easy way to look for a string and replace with another string
search("string") It returns first character position of string
match(regular expression) To check for formats likes 0336-3329998 or 111-111-2222, etc.
split(",") Split a string using a specifier. If separator found it will split into two or more elements in an array.

4. How to Define a New Object in JavaScript?

You can create as many as JavaScript objects you like, once you define an object’s structure.
It’s really easy to create a JavaScript object and to use it. This is how we can define a JavaScript object:

//StudentInfo type with four properties 
function StudentInfo(studentID, studentName, admissionDate, remarks) { 
    this.studentID = studentID; 
    this.studentName = studentName; 
    this.admissionData = admissionDate; 
    this.remarks = remarks; 
}

//defining method getStudentID() for StudentInfo type – getter 
StudentInfo.prototype.getStudentID = function() { return this.studentID; }

//defining method setStudentName() student name - setter
StudentInfo.prototype.setStudentName = function(newStudentName) { 
    this.studentName = newStudentName; 
}

Did you notice? In function and object definition we have difference of a keyword this. You defined method for this object using objectName.prototype. and yourNewFunctionName and modify the property of same object with using this keyword. Remember, This will allow you to modify object’s instance properties with these methods once you instantiate this object.

You can create any number of methods for your new object you want. Simply, by typing
ObjectName.prototype.yourNewFunction and start playing with your program to get productive in real-world programming.

Next Steps… Interacting One or More Objects Together As expected, a single can’t provide you a good solution of your problem. Thus, you need to have another object will require interaction of both objects data to add more details to your program while keeping organized. For this, you’ll have to create relationship with objects programmatically and that’ll be discussed next…

Comments

Popular posts from this blog

My Mission

How HTML Forms Works with JavaScript and Optimize Your Productivity with JQuery

How to Use JavaScript to Do Calculation and Make Decisions in Your Website???…