Sunday, December 25, 2016

19-Qs and As links


Javascript Questions links
  1. http://upworktest.in/top-10-popular-test-answers/javascript-test-2016/( (167 questions))
  2. http://www.freelancehelps.com/2015/09/javascript-test-answer-2015.html( has 88 question , same as in link 1.)
  3. http://upworktestanswer2015.blogspot.com/2015/12/javascript-upwork-test-answers-of-2016.html (http://upworktestanswer2015.blogspot.com )
  4. http://upworktestru.com/javascript_test_2016_upwork_answers_questions/
  5. http://entireupworktestanswers.blogspot.com/2016/07/javascript-upwork-odesk-elance-test.html
  6. http://kourge.net/node/130 (all "typeof" and "undefined" related QnAs)
  7. http://answers-odesk.blogspot.com/2014/05/javascript-13-test-answer-for-odesk.html
  8. http://upwork-odesk-answers.blogspot.com/2016/11/javascript-test-2016.html(167 exact same as 1. )
http://www.odeskupwork.tk/2016/08/javascript-questions-and-answers-2016.html


Application on Amazon RDS

http://www.w3schools.com/js/

Thursday, December 22, 2016

Javascript-18-JSON to JS Objects




Converting a JSON Text to a JavaScript Object


<html>
<body>
<h2>Create Object from JSON String</h2>
<p id="demo"></p>

<script>
var text = '{"employees":[' +
'{"firstName":"John","lastName":"Doe" },' +
'{"firstName":"Anna","lastName":"Smith" },' +
'{"firstName":"Peter","lastName":"Jones" }]}';

obj = JSON.parse(text);
document.getElementById("demo").innerHTML =
obj .employees[1].firstName + " " + obj.employees[1].lastName;
</script>

</body>
</html>



Output : Anna Smith

______________________________________________

Note:

comments of the form //… or /*…*/ are not allowed in JSON. This answer is based on:

_______________________________________________

Javascript-17-Hoisting Declaration, use strict keyword


Hoisting
(meaning, recognizing a variable prior to its declaration):

Javascript Hoists only declaration(var x;). 
But , not initiations(var x=9; (or) x=9);

Example:

(a)
<body>
<p id="demo"></p>
<script>
x = 5; // Assign/initialize 5 to x
elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x                // Display x in the element
var x; // Declare x
</script>
</body>

(b)
<body>
<p id="demo"></p>
<script>
var x; // Declare x
elem = document.getElementById("demo"); // Find an element 
elem.innerHTML = x                    // Display x in the element
x = 5; // Assign/initialize 5 to x
</script>
</body>


(a) results in "5", which is the value assigned for "x", though x has been defined after it is used. However, x has been initialized much before its usage.

(b) results in "undefined", though "x" has been defined before its usage. However, x has been initialized after its usage.

Hence, javascript hoists only for initializations and not declarations.

___________________________________

use strict;

This statement is used in order to ensure that the developer initializes and declares all his variables before its usage.

The "use strict" directive is only recognized at the beginning of a script or a function.

referhttp://www.w3schools.com/js/js_strict.asp to check onmore of the keyword notes



_________________________________________________________


Javascript-16-Regex



Regular Expression

Syntax: /pattern/modifiers;

pattern - the string pattern that needs to be searched
modifiers - the condition if any during the search for the pattern.

Regular Expression Modifiers:

iPerform case-insensitive matching
g - Perform a global match (find all matches rather than stopping after the first match)
m - Perform multiline matching


Regular Expression Patterns:

[abc] - Find any of the characters between the brackets
[0-9] - Find digits in the range in the brackets
[x|y] - Find x or y giving in the bracket


Metacharacters:





Quantifiers:





______________________________________

Regular expressions can be used with 2 of String methods:

1)str.search(""); //returns index of first occurence
Example:

  • var str = "Visit W3Schools"
  • var n = str.search(/w3schools/i); // returns 6


2)str.replace(""); //returns string by replacing string occurence
Example:
  • var str = "Visit Microsoft!";
  • var res = str.replace(/microsoft/i"W3Schools"); //returns Visit W3Schools! for "res" value
______________________________________

Regex Object and its methods:

test(): It searches a string for a pattern, and returns true or false, depending on the result.

  • var patt = /e/;
    patt.test("The best things in life are free!"); 
  • (or) 
  • /e/.test("The best things in life are free!");
  • Results in "true"

exec()It searches a string for a specified pattern, and returns the found text. If text not found, returns null;

  • /e/.exec("The best things in life are free!");
  • Results in "e"

______________________________________

Javascript-15-Bitwise operations



Bitwise Operations


Notes: 
  • JavaScript uses 32-bit signed numbers.

Bitwise AND : 1&1 = 1, else 0


Bitwise OR0|0 = 0, else 1


Bitwise XOR1^1 = 1, 0^0 = 1, else 0


Bitwise ~ : 

~5 =>  (bitform of the number+ 1). 

  • Another trick is, ~(number) = -(number+1). ie, ~5 = -(6)

Bitwise -(negation)

However, -(5) = retain last digit and swap the rest.
ie, -5 
5 = 00000000000000000000000000000101
-5 = 11111111111111111111111111111011


(Zero Fill) Bitwise Left Shift (<<): 

  • 5 << 1 = 10; ie, 
    • 00000000000000000000000000000101 
    • <<
    • 1
    • 00000000000000000000000000001010 (ie, 000..0(2power3)0(2power1)0


(Zero Fill) Right Shift (>>>):

  • 5 >>> 1 = 2; ie, 
    • 00000000000000000000000000000101 
    • >>>
    • 1
    • 00000000000000000000000000000010 (ie, 000..0(2power1)0 == 2)

(Sign Preserving) Bitwise Right Shift (>>): 

  • -5 >> 1 = -3; ie, 
    • 11111111111111111111111111111011
    • >>
    • 1
    • =
    • 11111111111111111111111111111101 ---(a)
    • here's the trick, 
      • shift 1 place in bit format to get (a) and 
      • retain last digit after  and 
      • swap the rest. Now u get a decimal. 
      • add -ve to the obtained decimal.. hence in the above case..
      • 00000000000000000000000000000011 .. which is 3. 
      • Now add -ve to 3.. hence -3
______________________________________________

Decimal to Binary function:

function dec2bin(dec){
    return (dec >>> 0).toString(2);
}


Binary to Decimal function:

function bin2dec(bin){
    return parseInt(bin, 2).toString(10);
}


______________________________________________

Javascript-14-For Loops



For Loops



  • For loop: for(initiation(optional),condition,increment(optional))

    • var i = 2;
      len = cars.length;
      var text = "";
      for (; i < len; i++) { 
          text += cars[i] + "<br>";
      }
    • If you omit statement 2, you must provide a break inside the loop. Otherwise the loop will never end. This will crash your browser.


  • For in: for(variableName in objectname)

    • var person = {fname:"John", lname:"Doe", age:25}; 
      var text = "";
      var x;
      for (x in person) {
          text += person[x];
      }
It is a common mistake, among new JavaScript developers, to believe that this code returns undefined:
It is true in many programming languages, but not true in JavaScript.

Example:
for (var i = 0; i < 10; i++) {// some code}
return i;

The code returns value of i as "10", though ideally it is out of the for loop. Thats how it is in javascript

_____________________________________________________________



Javascript-13-Boolean datatype


Boolean datatype

    • Boolean(10 > 9);// returns true
    • (10 > 9)       // also returns true
    • With "REAL" or "static" value returns "false"
      • var x = 0;Boolean(x);// returns false
      • var x =-0;Boolean(x);// returns false
      • var x ="";Boolean(x);// returns false
      • var x;Boolean(x);// returns false
      • var x =null;Boolean(x);// returns false
      • var x =false;Boolean(x);// returns false
      • var x =10/"H";Boolean(x);// returns false
    • var x = false;var y = new Boolean(false);
      // typeof x returns boolean // typeof y returns object
    • var x = false;var y = new Boolean(false);
      • (x == y) is true because x and y have equal values
      • (x === y) is false because x and y have equal values
    • var x = new Boolean(false);             
      var y = new Boolean(false);
      • (x == y) is false since x and y are 2 different objects



-------------------------------------------

Javascript-12-Datatype Object object


Object object
  • written with curly braces.
  • seperated by commas.
  • written as name:value pairs. Example of object with 4 properties: 
    • var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue", fullName : function() {return this.firstName + " " + this.lastName;};
  • Access Object properties in code. Example:
    • objectName.propertyName
    • ie, person.firstName; (or) person["firstName"];
  • Access Object functional property in code. Example:
    • Refer Example(Object) below:
    • objectName.methodName() 
    • ie, name = person.fullName (); 
    • (or) name = person.fullName ;
  • Adding property to an object in code. Example:
    • objectName.newPropertyName ="newPropertyValue" 
    • ie, person.city = "california"
  • Deleteing property from object in code. Example:
    • delete objectName.newPropertyName; 
    • ie, delete person.city;  (or) delete person["city"];   

--------------------------------------------------

Example(Object)
<html>
<body>
<p><b>Object Function Call Demo</b></p>
-----------------------------------<br>
<b>ACCESS function with "()"</b>
<p id="demo1"></p>
-----------------------------------<br>
<b>ACCESS function without "()"</b>
<p id="demo2"></p>

<script>

var person = {
    firstName: "John",
    lastName : "Doe",
    id       : 5566,
    fullName : function() {
       return this.firstName + " " + this.lastName;
    }
};

document.getElementById("demo1").innerHTML = person.fullName();

document.getElementById("demo2").innerHTML = person.fullName;
</script>
</body>
</html>


O/P:
Object Function Call Demo
-----------------------------------
ACCESS function with "()"

John Doe
-----------------------------------
ACCESS function without "()"

function () { return this.firstName + " " + this.lastName; }


--------------------------------------------------

SORTING : sort() an object, USING compare function
  • sort() an Object array (wrt Integer properties)
    • var cars = [
      {type:"Volvo"year:2016},
      {type:"Saab"year:2001},
      {type:"BMW"year:2010}];
      • cars.sort(function(a, b){return a.year - b.year});
      • //sorting wrt year in ascending order.
  • sort() an Object array (wrt String properties)
    • cars.sort(function(a, b){
          var x = a.type.toLowerCase();
          var y = b.type.toLowerCase();
          if (x < y) {return -1;}
          if (x > y) {return 1;}
          return 0;
      });//sorting wrt String properties in ascending order.

--------------------------------------------------

FREEZE: Object.freeze(object variable) 
  • calling freeze on an object ignores all operations on the object, that r performed after the freeze call.
  • Example:
    • <script>
      var variable1 = { fastFood: “spaghetti”, length: 10 };
      Object.freeze(variable1); --(a)
      variable1.price = 50;
      delete variable1.length;
      </script>
    • O/p :  all operations after --(a) are ignored and Object variable1 remains unchanged.
--------------------------------------------------

JavaScript Objects are mutable:

If a new Object variable is created and initialized with an existing object,

it does not create a copy.
But only point to the same object.

Hence any changes made to any one of them, reflects in both object's operations. Here's an example to prove that:

Example :


<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
var person = {firstName:"John", lastName:"Doe", age:50, eyeColor:"blue"}

var x = person; // here, object x is pointed to Object "person" instead of copy creation
x.age = 10;  //Value of age property has been reassigned using "x", however, this also resets age for "person"
x.firstName="newName";
document.getElementById("demo").innerHTML =
person.firstName + " is " + person.age + " years old." + x.firstName;
</script>

</body>
</html>

O/P:
newName is 10 years old.newName

--------------------------------------------------

Creating a Prototype of an object: This just means to create a constructor for the Object that needs to be called.


Refer Example below:

<!DOCTYPE html>
<html>
<body>

<p id="demo"></p>

<script>
function Person(first, last, age, eye) {
    this.firstName = first;
    this.lastName = last;
    this.age = age;
    this.eyeColor = eye;
}

var myFather = nnew Person("John", "Doe", 50, "blue");
var myMother = new Person("Sally", "Rally", 48, "green");

document.getElementById("demo").innerHTML =
"My father is " + myFather.age + ". My mother is " + myMother.age; 
</script>

</body>
</html>

O/p:
My father is 50. My mother is 48
_________________________________________________

Adding Properties to a Prototype
  • 2 ways to add a new property to a prototype, you must add it to the constructor function: 
    • function Person(first, last, age, eyecolor) {
          this.firstName = first;
          this.lastName = last;
          this.age = age;
          this.eyeColor = eyecolor;
          this.nationality = "English"
      }
    • function Person(first, last, age, eyecolor) {
          this.firstName = first;
          this.lastName = last;
          this.age = age;
          this.eyeColor = eyecolor;
      }
      Person.prototype.name = function() {
          return this.firstName + " " + this.lastName;
      };
  • However, you cannot add property to a Object Prototype like u do for an Object.
    • Person.nationality = "English";//Not allowed.
    • doing so and accessing the property through a variable object returns "undefined"
    • var myFather = new Person("John", "Doe", 50, "blue"); myFather.nationality; // returns "undefined"

--------------------------------------------------