Lecture 3: Primitive Data Types, Data Structures, Array properties and methods, Objects, JS built-in objects, Meet JSON, DOM



Number, String, Boolean They have their native methods(functions). User defined methods cannot be added.
var a = "This is Kathmandu", b=3, c=true;
a.length(); a.indexOf("th"); a.substr(5,2);
b.toString(); b.toPrecision(2);
Boolean(b);


Homework - Make a note of all String methods from w3schools String Methods. Try the methods in the console of your browser. - Make a note of all Number methods from w3schools Number Methods. Try the methods in the console of your browser.

Data Structures

- Arrays and Objects are JavaScript data structures built from primary data types - Array is a list of primary data types. It can contain any kind of data, even functions.
var arr = ["new", "old", "used", "broken",true, 5,
        function aFunction(){console.log("function executed")}];
console.log(arr);
document.getElementByID("idOfAnElement").innerHTML = arr;
- Access particular item of an array
arr[3]; // index start from 0
    console.log(arr[6]);
    //or
    document.getElementById("idOfAnElement").innerHTML = arr[6];//returns function definition in above array
    arr[6]();//executes the function

Array properties and methods

Length Property
 var a=["Nokia", "Panasonic", "Vertu", "Samsung"];
    a.length;
    a[4]="Apple";//add element in the array
    a[a.length] = "Blackberry";
    a[0]="Microsoft"; //change item at index 0
    a[10]="Colors"; //add item at random index, creates holes


Array Methods

 a.sort(); //sorts the element in a in alphabetical order
    document.getElementById("someElement").innerHTML=a.valueOf();
    a.join(" and ");//joins the items with the text argument
    a.pop(); //remove last element
    a.push("LG");//add a new element
    a.splice(2,1,"Nottel","ZTE"); // removes 1 element at index 2, and adds rest of the arguments at that position
    a.splice(2,1); //remove 1 element at position 2. 


Homework Make a note of all Array Properties and Methods from w3schools Array Methods. Make an array of your own and try executing all the Properties and Methods on your array in the console of your browser. Make a note if you see any odd behaviour of the array methods.

Objects

Object is a collection of values as name:value pairs.
  var person = {
    firstname: "Udeep",
    address: "Kathmandu",
    age:28,
    changePlace: function(newAddress){ this.address=newAddress;}
    }
    //firstname is a Propety of object person, changePlace is a method of object person
this is a keyword. It always represents an object, in fact, the object which owns the javascript code the keyword is used in.

Accessing properties and methods of an object

Use property or method names with the object name to access values in the object
console.log(person.firstname);
    //or
    person["firstname"];
    person.changePlace("Pokhara") //Note the parenthesis appended in the method name


Objects are just like arrays. The only difference is that the array uses numbered index and the objects use named index.
var arr=["a","b"], obj={first:"a",second:"b"};
    arr[0];
    obj["first"];//Note the quotes
    obj.first;


Lets play with the object

 var obj={first: "a", second:"b"};
    var propname="second";
    obj[propname];
    obj.third="c"; //add new property or method
    delete obj.first;//removes the property or method
    console.log("second" in obj); //returns true if obj has property "second", or false if not
    var a = {fname: "Udeep", lname: "Shakya"};
    var b = {fname: "Udeep", lname: "Shakya"};
    var c = a; 
    console.log(a==c); //true because it's the same object referenced by two variable names
    console.log(a===c); //true
    console.log(a==b);//false because OBJECTS CANNOT BE COMPARED


 for(...in...)
    for(props in a){
    console.log(a[props]);
    }


Build an object type

Use object constructor to create an object type that can be used to create many objects of one type.
function Car(brand, model, build, type){
    this.brandName=brand;
    this.model=model;
    this.buildYear=build;
    this.category=type;
    }
    var car1 = new Car("Audi", "A6", 2010, "sedan");
    var car2 = new Car("BMW", "X6", 2012, "SUV");


- What happens to car2 if I add new property to car1 ???
 car1.engineType="quattro";


- How to add new properties in the object type??? See http://www.w3schools.com/js/js_object_pr…

- Can array contain objects?
var obj={
models:["Seat","Ford"],
types:["sedan","hatchback","SUV"]
};

var arr=[ {brand:"Nokia", model:"6600"}, {brand:"Apple", model:"iPhone6 plus"} ];


JS built-in objects

Boolean Eg. var x1 = new Boolean(); Number Eg. var x2 = new Number(); String Eg. var x3 = new String(); Date Eg. var x4 = new Date(); Math Regular Expressions Eg. var x5 = new RegExp(); Array Eg. var x5 = new Array(); Function Eg. var x7 = new Function(); Object Eg. var x8 = new Date();

Note: You can add new properties or methods to above objects when defined with new keyword but this kind of definition slowers the execution. Don't declare variables this way except for Date objects.

Meet JSON



- JavaScript Object Notation (JSON) is used as a data storage and communication format on the Web - Language Independent - Name:Value pair just like objects in JavaScript
"fname":"Udeep" //JSON Data

"people":[ {"fname":"Siya", "lastName":"Something"}, {"fname":"Sheetal", "lastName":"Something"} ] //JSON Array {"fname":"Siya", "lastName":"Something"}//JSON object


JSON to JavaScript Object and otherway

- Convert JSON string to Object
 var newObj=JSON.parse('{"fn":"Siya", "ln":"any"}');
    console.log(newObj.fn);//"Siya"

- Convert Object to JSON text *``var obj = {first:1, second:2}; var text = JSON.stringify(obj);
If undefined, a function, or a symbol is encountered during conversion it is either omitted (when it is found in an object) or censored to null (when it is found in an array).

Want to learn more? Visit https://developer.mozilla.org/en/docs/We… and https://developer.mozilla.org/en-US/docs…

Try it yourself
JSON.stringify(
{ one: 1, two: 2 , three:null, four:""}, null, '\t', 
{five:5, six:function(){return 1}}
);


JSON.stringify(
[{ one: 1, two: 2 , three:null, four:""},
{five:5, six:function(){return 1}}]
);


JSON.parse('[1, 5, "false"]'); // [1, 5, "false"]
JSON.parse('{"p": 5}', function(key, value) {
  if (key === "") { return value; }//if topmost value, return it
  return value * 2;// else return value * 2.
});


Exercise - Create an object type to store the following information about a movie: title (a string), duration (a number), and stars (an array of strings). Make array of your 5 favorite movies. Show the information of 1 movie at a time in a row of a Table with table headers Title, Duration in Minutes, Stars. - Put "Previous" and "Next" buttons. The row of the table should show information of second movie when Next button is clicked. Similarly, button with label "Previous" should show information of previous movie. - When user clicks on any cell of the movie row, the web page should show movie information as a sentence in a label. E.g. "Terminator 2 lasts for 90 minutes. Stars: Arnold Schwarzenegger, Linda Hamilton."

DOM relations

View figure 1

DOM Manipulation

Select DOM Elements
var labels = document.getElementsByTagName("img");
console.log(labels[0].src);


var myLink=document.getElementById("lnktow3");
myLink.style.color="green";


var myClassElms=document.getElementsByClassName("sideContents");
console.log(myClassElms[0].tagName);


Create DOM Element

var para = document.createElement("p");
var node = document.createTextNode("Just text");
para.appendChild(node);//not yet added to document
document.body.appendChild(para);//added to the end of the doc


var btns = document.body.getElementsByTagName("button");
document.body.insertBefore(para,btns[0]);
//adds first argument before the node in second argument


DOM Manipulation



Replace DOM element
var image= document.getElementById("catImage");
var text = document.createTextNode("Cat");
image.parentNode.replaceChild(text,image);


Remove element
var lbltoRemove = document.getElementById("lbl1");
lbltoRemove.parentNode.removeChild(lbltoRemove);


Set and Get custom attributes
var myObj = document.getElementById('visit1');
myObj.setAttribute('place','Nagarkot');
alert(myObj.getAttribute('place'));


Query Selector
document.querySelector("CSS selector"); //gets first element


CSS Selectors - "p" - tag name - "#someId" - Id Name -".comment" - Class name - "[attr]" - Attribute name

document.querySelectorAll("CSS selector");
//gets all element as an array-like object


document.querySelector("p");
document.querySelectorAll("p.example");
document.querySelector("a[href='www.naya.com.np']");