Showing posts with label javascript. Show all posts
Showing posts with label javascript. Show all posts

Saturday, September 8, 2018

Generally asked MEAN stack question part 2

Questions:

1. Digest cycle https://www.youtube.com/watch?v=SYuc1oSjhgY

2. $watch,$watchCollection and $watchGroup

3. How change detection work in angular js

4. Why we use link from CDN

5. What is blocking and non-blocking in node

6. $ajax callback, Complete and Done.

7. {{}} and ng-Bind

8. $httpclient

9. Closure function in javascript

10. Directive lifecycle in angular

11. How change detection work in angular

12. Component lifecycle hooks

13. Difference b/w onChange and doChange

14. Difference b/w constructor and onInit

15. Which type of work we do in constructor and which type of work we do in onInit

16. What is the use of $resource

17. prototype in javascript

18. Inheritance in javascript

19. scope life cycle

20. $digest loop

21. Difference b/w javascript and node js

Sunday, October 29, 2017

Javascript Data Types

There are two basic data type in javascript:

Note:

  1. Javascript variable are dynamic type. It means when we assign value to javascript variable then data type of that variable will depend on the type of value the variable holds.
  2. typeOf operator is used to find the data type of the variable.

Primitives
  1. string
  2. boolean
  3. number
  4. undefined
Non Primitives
  1. object
  2. function
string: When we declare a variable by assigning the value to the variable in single quotes i.e. ' ' or in double quotes "". then that variable become of string type.

Example: 

var name="abc";
or
var name='abc';


boolean: When we declare a variable by assigning the value to the variable true/false then that variable becomes of boolean type.

Example:

var flag = true;
or
var flag = false;

number: When we declare a variable by assigning the integer or floating value to the variable then that variable becomes of number type.

Example:

var salary=5000;

var salary=5000.543;

var salary=5.324e+2;

var salary= 5.324e-4;

undefined: When we declare a variable and does not assign any value to it then then that variable becomes of undefined type.

Example:

var name;

Non Primitive:

object: Object data type variables are reference type.

Example:

var name=null; //null is a keyword and its type is object.

var myArr=[1,2,"5"]; // data type of the array is object

var obj={ firstName : 'shshi' , lastName: 'sharma'};

 Note: 

  1.   In javascript we declare object with key-value pair. 
  2.   Key name can be any value. We can use key name as valid string value.
  3.   Value can be any valid javascript supported data type.
function: When we declare a function and assign function into a variable then data type of the variable becomes function.

Example:

var myFunc=function (){
      alert("hello");
}

Hope it helpful to know about javascript data type.

Thanks for reading.

Monday, July 18, 2016

Parse string to date in javascript

How “string” value can be parsed into “date” in javascript?

We can parse date from string using two methods:

Date.parse(datestring)

Or

new Date(dateString)

if dateString is according to the ISO-8601 or RFC2822 standard then it will return the valid converted date otherwise it may result unexpected result.

The Standard format is :YYYY-MM-DDTHH:mm:ss.sssZ

   ·      When we use the date.parse, it internally use the new Date(datestring)

   ·       After successfully parsing the date, it returns the date in the “number of milliseconds” since   January 1, 1970, 00:00:00 UTC.

   ·       In case of Date.parse(dateString) if date is invalid then it will return “NaN” and

   ·       In case of new Date(dateString) if date is invalid then will return “Invalid Date


Examples:

Date.parse("18/07/2016")

//result: NaN

new Date("18/07/2016")

//result: Invalid Date

Date.parse("2016-07-18")

//result: 1468800000000

new Date("2016-07-18")

//Result: Mon Jul 18 2016 05:30:00 GMT+0530 (India Standard Time)

There is one famous javascript library to Parse, validate, manipulate, and display dates in JavaScript.

You can go through it with the below link:



Saturday, July 9, 2016

Difference between for..in and for..of loop in javascript


There is an difference b/w the two javascript loop for..in and for..of
Ø  for..in:
The for..in loop works with array and objects. It iterates with the property name.
1.1    When working with array it returns the indexes of the array element and user defined properties.

eg.
var arr=[12,13,14,15];
arr.foo='abc';
for (index in arr)
console.log(index);  // use arr[index] to access the element
Result:
0
1
2
3
foo
1.2    When working with object it returns the ‘key name’ of the object.

Eg.
var obj={key1:12,key2:13,key3:14,key4:15};
for (key in obj)
console.log(key); // use obj[key] to access the element
Result:
key1
key2
key3
key4

Ø  for..of: It works only with iterable objects. Iterable objects are those object that use Iterable protocol.
Inbuilt iterable objects are Array, String, Map, Set, TypedArray. Iterable object have the @@iterator method (i.e Symbol.iterator key). It iterates with the property value.

Eg.
var arr=[12,13,14,15];
arr.foo='abc';
for (index of arr)
console.log(index);  
Result:
12
13
14

15

Monday, June 13, 2016

Calling RESTful API in Javascript


Here, we will call the RESTful API from javascript.

Suppose there is a RESTful API which URL is: http://localhost:8083/saveEmployeeDetail

And I want to save employee information using Javascript.

We will call the above API using “POST” method.

There is a button in html page which. When I will click this button it will save the employee information. Data is being sent in JSON format.

Here I am using “XMLHttpRequest” to call RESTful API.



1.  Testing.html

<!DOCTYPE html>
<html>
<head>
    <meta name="viewport" content="width=device-width, initial-scale=1">   
    <title></title>
</head>
<body ng-controller='loaderCtrl'>
    <input type="button" value="Submit" onclick="saveDetails()" />
    <script src="testing.js"></script>
</body>
</html>

2.  testing.js
var sendRequest = function (config, method) {
    if (!config) return;

    var ajaxHandler = new Object();

    if (window.XMLHttpRequest) {
        ajaxHandler.ajaxReq = new XMLHttpRequest();
    }
    else if (window.ActiveXObject) {
        ajaxHandler.ajaxReq = new ActiveXObject('Microsoft.XMLHTTP');
    }

    ajaxHandler.ajaxResponse = function () {
        // Only if req shows "complete"
        var readyState, status;
        readyState = ajaxHandler.ajaxReq.readyState;
        if (readyState == 4) {
            status = ajaxHandler.ajaxReq.status;
        }
        if (readyState == 4) {
            if (status == 200) {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come success                 
                 
            } else {
                document.writeln(ajaxHandler.ajaxReq.responseText);// here response will come  show failed message                

            }
        }
    }
    ajaxHandler.ajaxReq.onreadystatechange = ajaxHandler.ajaxResponse;
    ajaxHandler.ajaxReq.open(method, "http://localhost:8083/saveEmployeeDetail", true); // second parameter is the URl of the REST API
    ajaxHandler.ajaxReq.setRequestHeader("Content-type", "application/json;charset=UTF-8");
    //ajaxHandler.ajaxReq.headers = { "Authorization": "Basic " + btoa("admin:admin") };               
    ajaxHandler.ajaxReq.send(JSON.stringify(config));
}

function saveDetails() {
    var config = {
        "empID": 1001,
        "firstName": "Shshi Bhooshan",
    };

    sendRequest(config, "POST");
}



Hope this is helpful example for you. Leave your comment and provide your suggestion if any.

Wednesday, June 8, 2016

Array in Javascript

One of the most important object in javascript is Array object.

The Array in javascript is used to store the multiple value in a single variable.

Syntax:

var arrayVariableName=[item1, item2, item3];

or

var arrayVariableName=new Array(item1, item2,...);

Examples:

1. Assign values in array

var arr=[1,2,3,'a','b',1.5];

2. Add element in array
var arr=[1,2,3,'a','b',1.5];
arr.push("xyz");
console.log(arr);

//Result will be
[1,2,3,'a','b',1.5,'xyz'];

3. Remove Element from array:

var arr=[1,2,3,'a','b',1.5];

i) Remove last item:
arr.pop();

ii) remove the more then one item by:

arr.splice(0,1);// it takes two parameter fromIndex and No of element to remove

Result:
It will change the original array like below:
[2, 3, "a", "b", 1.5]

and return a new array also (list of the element removed) like below:
[1]

It also takes one more parameter to insert items form where item are being removed. 

arr.splice(0,1,'aaa','bbb')

Result:
it will return [1]

and

will modify the original array like below:
["aaa", "bbb", 2, 3, "a", "b", 1.5]




Friday, May 29, 2015

Trigger click event of a button using jquery

We can fire click event of a button in jquery as below:

Senario:  I am changing dropdown value and on change of dropdown value, click event of a button will be automatically fired displaying selected value of dropdown.

Example:


<html xmlns="http://www.w3.org/1999/xhtml">
<head runat="server">
    <title></title>
    <script src="http://ajax.googleapis.com/ajax/libs/jquery/1.11.2/jquery.min.js"></script>   
    <script>
        $(document).ready(function () {
            //test();
        });

        function changeOption() {           
           $("#btnSubmit").trigger("click");
        }

        function getName() {
            alert("automatic button has been clicked...." + $("#cars").val());
        }
</script>
</head>
<body>

    <div>
       <%--on click of drop down auto click of button will be done--%>
        <select name="cars" id="cars" onchange="changeOption();">
            <option value="volvo">Volvo</option>
            <option value="saab">Saab</option>
            <option value="fiat">Fiat</option>
            <option value="audi">Audi</option>
        </select>
        <input type="button" id="btnSubmit" value="Submit" onclick="getName();" />
    </div>

</body>
</html>






Thursday, January 8, 2015

Remove CSS Class using Jquery

We can remove css class in jquery like this-

Suppose we a “div” control like this :

<div id="divGrid" class="gridtable">
This is Test      
</div>

Here how we remove class from div-

$("#divGrid").removeClass("gridtable");

How to remove style using Jquery

We can remove style of an element in Jquery in the following ways-

Suppose we have a “div” control like this :

<div id="divGrid"style="max-height: 400px; overflow: auto; width: 100%;">
This is Test
</div>

      1.       Remove style attribute of the “div”

$("#divGrid").attr("style", "");//for remove style of div

    2.       Change width of the “div”

$("#divGrid").css("width", "1200px");// width of the div will be changed to 1200px

Saturday, January 3, 2015

getting css property value in jquery and applying css to an element in jquery

In jquery we can get the css value in following ways:

“.css” function is used to get css property of any element in jquery.

Example :

    <p style="font-size:20px" id="para1">
        Put content here.
    </p>

    <input type="submit" name="btnSubmit" value="Submit" onclick="return getBackColor();"        id="btnSubmit" />

function getBackColor() {
var color=$("p").css("font-size");
       alert(color);      
}  

We can set css to an element as following:

1.       Applying Single CSS

     $("p").css("font-size","30px");

2.       Applying Multiple CSS

     $("p").css({ "font-size": "30px", "color": "red" });



Note: We can use ID of the element also for applying css or getting value of css like $("#para1").css

Scope of a variable in javascript

Global scope of a variable:

When we declare a variable outside of a function then that variable has the global scope.
This type of variable can be accessed anywhere in the program or file.

Example:

var str = "test value";

It can be used anywhere in the program.

Local scope of a variable:

When we create a variable inside a function body then that variable has the local scope.
This type of variable cannot be accessed outside the function.

Example:

function getResult() {
    var result = 10;
    alert(result);
}

Note 1: When we do not declare a variable with “var” inside a function then
that variable can also be accessible outside of the function. Hence it has global scope.

Example:

<asp:Button ID="btn" runat="server" Text="submit" OnClientClick="getResult();" />

function getResult() {
    result = 10;   
    test();
    return false;
}

function test() {
    alert(result);//result will return 10 which is declared in getResult()
    return false;
} 


Note 2: When we define nested function then inner function has access to the variable defined in outer function but outer function cannot access to the variable defined in inner function.

Example:
function getResult() {
    var result = 10;

    function test() {
        var str = "Test";
        alert(result); //output will be 10
        return false;
    }

    alert("str" + str);// str will not be accessible
    return false;
}

Friday, January 2, 2015

Redirect to another page using jquery

We can redirect to another page following way

var url = "about.aspx" //url for redirect
$(location).attr("href", url);

Redirect to another page using javascript

We can redirect to another page using javascript in following ways:

1.  window.location.href = "default.html";//url of the page
2.  window.location.replace("default.html");//url of the page

Redirect to the parent page:

1.  window.parent.location.replace("default.html");//url of the page
2.  window.parent.location.href="default.html"; //url of the page

Thursday, January 1, 2015

get element by id javascript

Suppose we have a textbox in html and we want to know the value of the textbox then
in javascript we can get the element by two ways:

1.  document.getElementById
2.  document.getElementsByName


<input type="text" id="txtName" name="txtName" value="Mathew" />


function getName() {

    var Name = document.getElementById("txtName").value;
    var Name1 = document.getElementsByName("txtName").value;

    alert(Name);
    //alert(Name1);
}


It will display value in textbox by using “.value” attribute.