Constructor function

Object can be also be created with the following two steps :

1. By writing a constructor function, define the object type. It would be better if we use a capital initial letter.
2. create an instance of obj with new.

To define an object type, create a function for the object type with its specified name, properties and its method. For example :

function Person(name, age, gender){
    this.name = name;
    this.age = age;
    this.gender = gender;
}

this keyword is to assign values to the object properties based on the value which we have passed to it to the function.

Now, create an object called humans :

var humans = new Person('ram',20,'male');

This creates humans and assign it to the properties with the specified values.

To retrieve these values : humans.name // "ram"
                                         humans.age // 20
                                         humans.gender // "male"

If we want to redefine the object Person. we can add the properties.

function Person(name, age, gender, city){
    this.name = name;
    this.age = age;
    this.gender = gender;
    this.city = city;
}

var details = new Person('sita',20,female,Hyderabad);

To retrieve these properties : 

details.name // "sita"
details.age // 20
details.gender // female
details.city // Hyderabad

we can always add a property for a previously defined object. For example

details.study = "B.E";

Adds this property to the details object and this doesn't effect the other object.


objects

A JavaScript object has properties associated with it. A property of an object is explained in a variable which is been assigned to an object. The properties of an object can be accessed with a simple dot-notation.

Syntax :

objectName.propertyName

objectName and propertyName both are case-sensitive. property of an object can be defines the characteristic of an object. For example, let's create an object named person and give its properties named name,place,age and gender as follows :

var person = new Object();
person.name = "ram";
person.place = "Hyderabad";
person.age = 25;
person.gender = "Male";

If the properties of an object are undefined (not null)

person.dob // undefined

The properties of an object can also be set or accessed using bracket notation. Objects are sometimes called as associative arrays. As each property can be accessed with a string value can be used to access it. For example,

person['name'] = "ram";
person['place'] = "Hyderabad";
person.['age'] = 25;
person.['gender'] = "Male";

If a property name starts with a number or hyphen or contains space will not be a valid JavaScript identifier. The square bracket notation is very useful when property names are been determined dynamically.

creating 4 variables and assigning it in a single way, separated with comma(,).

var myobj = new Object();
      mystr = "myString";
      randomNo = Math.random();
      newObj = new Object();

myobj.type = "dotSyntax";
myobj['newstring'] = "This is a string";
myobj[mystr] = "This key is defined in mystr variable";
myobj[randomNo] = "Random Number";
myobj[newObj] = 'This is an Object';
myobj[' '] = 'empty string';

console.log(JSON.stringify(myobj));

output :

{
     "type":"dotSyntax",
     "newstring":"This is a string",
     "myString":"This key is defined in mystr variable",
     "0.6610736800691552":"Random Number",
     "[object Object]":"This is an Object",
     " ":"empty string"
}


All the keys in square bracket notation are converted to a string type. objects in JavaScript can only have string type as key type.JavaScript will call the obj.toString().

Bracket notation can be used in for..in to iterate overall enumerable properties of an object. 

For example : 

function showProperties(obj,objName){

       var result = ' ';
       for(var i in obj){
           if(obj.hasOwnProperty(i)){
                     result += objName + '.' + i + '=' + obj[i] + '\n';
           }
       }
    return result;
}

showProperties(person,"person");

output :

This result returns : 

"person.name=ram
 person.place=Hyderabad
 person.age=25
 person.gender=Male "

Enumerate the properties of an object :

Starting with the ECMAScript 5, there are three native ways to list the object properties.
  • for...in loops
  • Object.keys(o);
  • Object.getOwnPropertyNames(o);
for...in loops :

for..in statement iterates over the enumerable properties of an object. 

Syntax :

for( variable in object) {
.............
}

variable is a different property name i.e, assigned to variable on each iteration.

object is whose enumerable properties are iterated.

A for....in loops iterates over all enumerable properties of the object itself.

Deleted, Added or modified properties :

A for....in loop iterates over the properties of an object in an arbitrary order. If a property is modified in one iteration then later if we visit, we get the update value. If the property is deleted before, then its value is not visited any more. Properties added in the object may be iterated or can be omitted. It would be better not to add,modify or delete the properties during iteration.

Array iteration :

Array indexes are an enumerable properties with integer names and the for...in may not return in any particular order.

The example for for...in is discussed above.

Object.keys() :

This returns the array of given objects in the same order as provided in the for..in loop.

Syntax :

Object.keys(obj)

Examples :

var obj = {'a' : 0, 'b' : 1, 'c' : 2};
console.log(Object.keys(obj));

output :

"a","b","c"
//with random key
var obj1 = {100 : 'a',1 : 'b' , 2 : 'c'};
console.log(Object.keys(obj1));

output : 

1, 2 , 100

Object.getOwnPropertyNames() :

This method returns an array of all properties which are been found in the given object. It returns an array whose elements are strings which can be enumerable or non-enumerable  properties, found in the obj. The ordering of these properties are not defined.

Syntax :

Object.getOwnPropertyNames(obj);

Examples :

var arr = ['a', 'b'];
console.log(Object.getOwnPropertyNames(arr).sort()); 

output :

[ "0", "1" , "length"]

var obj = { 0: 'a', 1: 'b', 2: 'c' };
console.log(Object.getOwnPropertyNames(obj).sort()); 

output : 

["0", "1", "2"];

Object.getOwnPropertyNames(obj).forEach(
  function (val, idx, array) {
    console.log(val + ' -> ' + obj[val]);
  }
);

output :

0 -> a
1 -> b
2 -> c



Keyed Collections

Maps : 

Map object : 

ECMA Script has introduced a new data structure from map values to values. A Map object contains a simple key/value map and can iterate in it's insertion order.

Example :

var sentences = new Map();

for this variable sentences we can set values i.e,

sentences.set("she" , "cute")
Here, she is a key and cute is a value.
sentences.set("He" , "back");
sentences.set("It" , "cool");

To know the size :

sentences.size; // 3

To get the value:

sentences.get('hello'); //undefined

sentences.get("she"); //cute

To delete a key/value pair :

sentences.delete("It");

To check whether the key/value pairs exists in the variable

sentences.has("He"); //  It returns a boolean value if the value exists i.e, true

sentences.has("the"); // false

Now retrieving the values :

for(var [key, value] of sentences){

       console.log(key + "is" + value);

}

output :

she is cute
He is back

To delete all the key/value pairs :

sentences.clear(); // all the key/value pairs are been deleted.

sentences.size; // 0

Comparison between Map and object

object are been used to map strings to values. It allows you to set keys to values, retrieve those values, delete those values etc. The iteration of maps is done in the insertion order of elements. The keys of an object are strings. Size of  map is easily known. As, it is shown in the above example. we have to keep track of the object to know the size manually. An object has a prototype and there are default keys in map.

WeakMap object :

It is a collection of key/value pairs in which keys will be objects only and values can be our choice.
The weakmap meaning is if there is no reference to the object, then it is targeted as a garbage collection. The difference between Map and WeakMap : It is not enumerable i.e, it has no methods to show the list of keys.

          WeakMap objects is stored as private. It is accessed only with in inside the object and are stored in private weakmap object.

Set object :

set object is collection of values. It can done in insertion order. A value in set can occur only once, i.e, it maintains only unique values.

var sets = new Set();

sets.add(100)
sets.add("hello");
sets.add("blogger");

sets.has(100); //true
sets.delete("hello"); //deleted
sets.has("hello"); // false
sets.size; //2

To retrieve the items from the sets variable :

for(let items in sets){

         console.log(items);   

}

output : 

//100
//blogger

Conversion of Array to set and vice-versa :

Arrays from set can be created i.e, through Array.form or the spread operator and also the set accepts to convert the array in other ways. As, set object only stores the unique values. So, any duplicate element from a array is deleted when converting it to the set.

Comparison between  Array and Set :
  • checking whether the elements exists in the array using indexOf for array is slow, whereas in set can be known using has().
  • set object let you to delete elements using their value whereas in array need to splice it based on it's element index.
  • set object stores unique values, no need check or keep track of duplicate values.
  • The value NaN cannot be found in indexOf in array.
WeaskSet objects :

Weakset objects are collection of objects and it may occur only once. It is unique in the weakset's collection and it is not enumerable.
If there is no other reference for the object in the weakset, then it is garbage collected.













JSON.parse()

JSON.parse() method parses a JSON string, constructing the JavaScript values or an object which is described by the string. A reviver optional function can be provided to perform some transformation on the given object before it is returned.

Syntax :

JSON.parse(text[, reviver])

Parameters :

text :

The string to parse a JSON .

reviver : (optional)

This specifies how the value will be produced by parsing it, before the result is returned.

return value :

It returns the object which is based on the given JSON text.

Exceptions :

If the string to parse is not valid then it throws a syntax error.


Examples :

JSON.parse('{}') // {}
JSON.parse('true') // true
JSON.parse('"hello"') // "hello"
JSON.parse('[1,2,3]') // [1,2,3]
JSON.parse('null') //null

parameter : reviver

reviver specifies the value computed by parsing is transformed before it is being returned, the values and its properties will run individually through the reviver. Then it is called with the name and value i.e, name as String, value as argument. If reviver is undefined or no value then the property is deleted from the object.

Example :

1. JSON.parse( '{"no":10}', (key,value)  =>

typeof value === 'number'
          ? value * 10 // if typeof value is number then it returns 100
           : value // else it returns 10, the value will not be changed
);
output : 100

2. JSON.parse('{
"first": 1,
"second": 2,
"third": {
"fourth": 4,
"fifth": {
"sixth": 6
}
}
}
', (key, value) => {
console.log(key); 
return value; 
});

output : 

first
second
fourth
sixth
fifth
third

JSON.parse() doesn't allow trailing commas, it throws a syntax error. i.e,

JSON.parse('[1,2,3,]')

JSON.parse('{"name":"blog",}')


JSON(JavaScript Object Notation)

JSON(JavaScript Object Notation) is a light-weight data-interchange format. It is easy for humans to read and write. It is a text format that is completely  language independent but uses conventions that are familiar to the programmers of the languages including C,C++,Java,JavaScript,Python and many others. This all properties make JSON an data-interchange format. It can't be constructed or called.

JSON can be represented in two different structures :


  • A collection of name/value pairs.
  • An ordered list of values.
In JSON, there are different forms. They are :

object :

An object is the set of unordered set of name/value pairs. An object begins and ends with the braces {}. Each name is followed by : (colon) and the name/value pairs are separated by comma (,).

object : {          String      :         value           }

Example

var mainJson = {

         "person" : {
                   
                  "name"        : "sita",
                  "age"           :  20,
                  "gender"      : "female",
                  "place"        :  "Hyderabad"

           },
         "bicycle" : {
                  
                    "color"  :   "red",
                    "price"  :    "10000"
         
           }

}

This is a sample example of  JSON. The json data is defined in a variable called mainJson. These can be retrieved as :

To get the entire person details.

console.log(mainJson.person) //  this returns the output in object form i.e,
                                                     { 
                                                         "name"        : "sita",
                                                         "age"           :  20,
                                                         "gender"      : "female",
                                                         "place"        :  "Hyderabad"
                                                       }

To retrieve only name : sita

console.log(mainJson.person.name) // sita

String :

To return a JSON String :

A string is a sequence of zero or more Unicode characters, wrapped in double quotes and using backslash escapes.

console.log(JSON.stringify(mainJson.person)) // "{
                                                                                     "name":"sita",
                                                                                     "age":20,
                                                                                     "gender":"female",
                                                                                     "place":"Hyderabad"
                                                                                 }"
object
       {}
        { members }
members
       pair
       pair , members
pair
       string : value
array
       []
       [ elements ]
elements
       value
       value : elements
value
       string
       number
       object
       array
       null
       true
       false









Numbers

In JavaScript, all numbers are defined in double precision 64-bit binary format IEEE 754 i.e, the numbers between -(253 -1) and 253 -1). There are no Specific type for integers and to represent floating-point numbers, it has three symbolic values i.e, +infinity, -infinity and NaN(not a number).

There are four types of number literals. They are: decimal, binary, octal and hexadecimal.

Decimal Numbers

The Decimal literal can start with zero(0) and followed by another decimal digit. If any digit followed by zero(0) is smaller than number 8, than the number gets parsed as a octal number.

0888 // 888 parsed as decimal

0666 // parsed as octal

Binary Numbers

Binary number syntax starts with a zero(0) followed by a lower case or upper case Latin letter "B" (0B or 0b). If the digits after 0b are not followed by 0 or 1, then "Missing binary digits after 0B" syntax error is shown.

Octal Numbers

Octal Number syntax uses a leading zero. If the digits after 0 has range between 0 and 7 are defined as octal number otherwise it will be decimal number.

var a = 0453; //453
var b = 0333; //333

In ECMAScript 5, the octal numbers are supported if they are prefixed with 0o.

Hexadecimal Numbers

Hexadecimal numbers uses a number zero followed by a lowercase and uppercase Latin letter 0X. (0X or 0x). If the digits after 0x (123456789ABCDEF) doesn't follow these values then following syntax error is thrown i.e, Identifier starts immediately after numeric literal.

Ex: 0xFFFFFFFFFFFFFFFFF




Special Characters in Strings

There are many special characters used in the Strings. They are:

\0 Null String
\b Backspace
\f Form feed
\n New line
\r carriage return
\t tab
\v vertical tab
\' Apostrophe or single quote
\'' Double quote
\\ Backslash character

\XXX  This Character with in the Latin-1 encoding specified up to 3 octal digits between 0 to 377. For Ex : \150 is the octal sequence symbol.

\xXX  This Character with in the Latin-1 encoding specified up to 2 hexadecimal digits between 00 to FF. For Ex : \xA9 is the hexadecimal sequence symbol.

\uXXXX  This Unicode character specified up to four hexadecimal digits XXXX. For Ex: \uFFFF is the unicode character symbol.

\u{XXXX}  This is Unicode point escapes. For Ex: \u{2F804} is same as simpe unicode character \u2F804.



SampleExample


Click Me

typeof

typeof operator returns the type information as a string.

The typeof operator is followed by its operand.

operand is an expression which represents the object.

Examples :

Numbers

typeof 32 == number
typeof 45.67 == number
typeof(40) == number
typeof Infinity == number
typeof NaN == number // defined Not a Number
typeof Number(1) == number // but never go with this format

String

typeof '' == String
typeof 'hi' == String
typeof '22' == String
typeof (typeof 22) == String
typeof String('hello') == String // but never go with this format

Booleans

typeof true == boolean
typeof false == boolean

Symbols

typeof Symbol() == Symbol
typeof Symbol('hi') == Symbol

Undefined

typeof undefined == undefined
typeof undeclaredVariables == undefined
typeof declaredButNotDefined == undefined

Objects

typeof {"name" : "blog"} == object
//array
typeof [1,2,3] == object

Function

typeof function(){} == function
typeof class A == function
typeod Math.sin == function

null

typeof null == object

using new function

var name = new String('String');
var num = new Number(100);

typeof name == returns object
typeof num == returns object

var func = new Function(0
typeof func == returns Function

Regular Expressions

typeof /s/ ==  function // from chrome 1-12 and ECMAScript 5.1
typeof /s/ == object // from firefox 5+ to ECMAScript 5.1

Temporal errors

if variables are defined as const

const constantVariable = 'hello';
typeof constantVariable // reference error

Exceptions

typeof document.all == undefined

objects are objects but not function 

typeof alert == object

ECMA Script Scope

ECMAScript defines:

1. Language syntax. (parsing rules, keywords, control flow so on)
2. Error Handling Mechanisms. (try/catch, throw, can create user-defined error types)
3. Types (boolean,string,number,function so on)
4. Global objects like parseInt, parseFloat, decodeURI, encodeURI and so on. ECMA Script defines only the API's which is not specific to the browsers.
5. Strict mode.
6. Inheritance Mechanism.
7. Built in objects like JSON, Math and also functions.


Object Literals

iIt is a list of pairs with the defined name and it's associated values, enclosed in curly braces ({}).

Object can be defined as :

var colors = {
       
          "darkColors": {

                  "a" : "red",
                  "b" : "darkgreen"

           },
         "lightColor" : "cyan"
}

Now, let us see how to retrieve these object values

If we want to get key value pairs which are been listed in the darkColors

colors.darkColors  // { "a" : "red",   "b" : "darkgreen" }

If we want to retrieve only specific value then it can be described as :

colors.darkColors.a //red

colors.darkColors.b //darkgreen

colors.lightColor // cyan

Floating-point literals

Floating-point literals can be defined in following ways:

1. Decimal value can be assigned i.e, integer and preceded by + or  - sign.
2. Decimal point.
3. Fraction
4. Exponent (sign : e or E)

Exponent is a part of e or E followed by integer values with the sign + or - . Floating point literal must contain at least one digit and a decimal point (e or E).

Example :

4.5678
-2.3456
12.45E + 19
.2e.098


Array Literals

Array elements are enclosed in square brackets ([]). Array literals may contain zero or more elements. The values are specified in the array list and its length is set based on the number of arguments specified.

create an Array

var cars = ['BMW','AUDI','BENZ'];
cars[0] // 'BMW' the First element
cars[1] // 'AUDI' the second element
cars[2] //'BENZ' the third element

To find the length of an Array

console.log(cars.length) // 3

Access an Array item

console.log(cars[1]); //AUDI

console.log(cars[cars.length-1]); //BENZ

Looping an Array (forEach)

cars.forEach(function( item ,index ,array ) {

    console.log(item , index )
});

Displays all the values from the array with its specific index.

// BMW , 0
// AUDI , 1
// BENZ, 2

To Add the value at the end of the Array

var addingValues = cars.push('SWIFT');

To remove value from the end of the Array

var popLastValue = cars.pop(); // removes SWIFT from the end of the array
// [ BMW, AUDI, BENZ ]

To remove value from the front of the Array

var removeFirstValue = cars.shift(); // remove BMW from the first
// [ AUDI, BENZ ]

To add value from the front of the Array

var addValueAtFirst = cars.unshift('INNOVA');
// [ INNOVA,AUDI,BENZ ]

Find the index of an Array

var findIndex = cars.indexOf('AUDI');
// 1

To remove an item from an index position 

var removeItem = cars.splice(findIndex, 1); // To remove the item we have to know its index position and then splice it.

// [ INNOVA,BENZ ]

To remove more than one item from an index position

var chocolates = [ 'mango','kitkat','dairymilk','barone' ];
console.log(chocolates);
// [ "mango","kitkat","dairymilk","barone" ]

var pos = 1, n = 2;

var removedItems = chocolates.splice(pos,n);

Here, the n defined the number of items to be removed from the array and pos defines the start position from an array.

console.log(chocolates) // [ mango , barone ] the values which are left in the array

console.log(removedItems) // [ kitkat, dairymilk ] the values which are been removed from the array.

copy an Array

var copyArray = chocolates.slice(); // we use method slice to copy an array.
// [ mango , barone ]








Literals

Literals are used to represent values in JavaScript. These literals are fixed but not variables which are been provided in the script. They are

1. Array Literals
2. Boolean Literals
3. Floating-point Literals
4. Integers
5. Object Literals
6. RegExp Literals
7. String Literals

Function Hoisting

The function declaration is been mentioned first and not the function expression.
Example:

calling(); //calling

function calling(){

      alert("calling");

}

calling(); //Type Error calling is not a function.

var calling = function(){

     alert("calling");

};

Datatype Conversion

JS is a dynamically typed language. we don't need to specify data type of a variable when you declare it, and data types are converted automatically.

var post = 10;
The value can be reassigned as a string to the same variable, it will not cause any error message.
post = "blog"'

DataTypes

There are seven datatypes which are been defined. They are :

1. String //"Hi"
2. Boolean //true or false
3. Null // A special keyword null, in JS it is case-sensitive null is not same as NULL.
4. Number // 42 or 45.678
5. Undefined // whose values are undefined. var x;
6. Symbol // which are immutable and unique.
7. Object 

Constants

Constants are read-only, defined with the const keyword.
Ex: const price = 100;

constant should be initialized to a value and it cannot be re-declared.
You cannot declare a const with same name as a function name and declaring it in the same scope.

For Example :

function a() {};
const a = 15; // This will cause an error.

function a(){
     const a =15; // This will also cause an error.
     //statements
}

Properties of the object which are assigned are not protected and they are defined as:

const myObject= {'key': 'value'};
myObject.key = "Name";
myObject.value = "blog-spot";

Difference between primitive boolean value and boolean object

var booleanValue = new Boolean(false);

if(booleanValue) // this condition verifies to true

if(booleanValue == true) // this condition verifies to false

Falsy values

The following values are described as falsy values (also known as false):

1. undefined
2. null
3. an empty string ""
4. false
5. 0
6. NaN

All other values,other than these including all object evaluates true which are passed to a conditional statement.

what is variable scope?

when you declare a variable outside the function, then it is called as a global variable. when you declare a variable with in a function, then it is called as a local variable.

JavaScript ECMA Script does not have block statements ( if , for , while) scope.

For Example:

if(true){

     var x = 15;

}

console.log(x); // x is 15

where as, In ECMA script let declaration was introduced.

if(true){

     let x = 15;

}

console.log(x); // x is not defined

what is a function?

Something which looks like a variable name, and adds parenthesis to it called as a function.
Function takes parameters, which are defined in the parenthesis. More than one parameters are separated with comma.
For Example : alert() is a function. It shows a pop-up box, we need to send a "string" as a parameter to tell the function what to show in the pop-up box.

We can create our own functions. For example we will create a function which adds two numbers:

function add(no1,no2){
        var result = no1 + no2;
         return result;
}

add(5,5);

The advantage of using return statement is, it tells the browser to use the result variable out of the function.

what is the difference between '==' and '===' ?

For example

var name1 = 'shruthi';
var name2 = 'SHRUTHI';

if(name1 == name2) ---> returns true because this is not case sensitive.

if(name1 === name2) ---> returns false because this is case sensitive.

Variables

Variables are containers, you can store data by defining a keyword called var.

var name;
name = 'shruthi';
This var keyword can contain a value of any datatype i.e
String:
var name = 'shruthi';

Number:
var count = 10;

Boolean:
var online = true;

Array:
var myArray = ["hello","hi"];
This can be retrieved as :

myArray[0] = 'hello';
myArray[1] = 'hi';

Object:
 Anything which can be stored in a variable can be defined as an object. The above mentioned examples too.
<div class='myClass'>hello</div>
<script>
var myObject = document.querySelector(".myClass").style.backgroundColor = "red";
</script>





Sample Example

1. First create a Folder named "Scripts" and add a file with a name called "sample.js" and save it in the folder. The JS files has to be given the extension ".js".
2. Save a index.html file in the same folder.
Need a add script tag to with the source sample.js

In index.html
<script src="sample.js"></script>

In sample.js
alert("Hello World");

The alert popup will be displayed with the message "Hello World" as soon as your page is loaded.




What is Javascript?

JavaScript is a full-fledged programming language. Invented by Brendan Eich, the Mozilla Foundation and the Mozilla Cooperation . It allows to solve the complex solutions on web pages.  It can provide dynamic interactivity and it is incredibly versatile. 

Overview of AngularJS

AngularJS is an open source web application framework. It is now maintained by Google . The most of the code can be eliminated by using th...