Thursday, 2 July 2015

Javascript - 5

1).What is JavaScript?
Ans:-JavaScript is a scripting language most often used for client-side web development.


2).Difference between JavaScript and Jscript?
Ans:-Both JavaScript and Jscript are almost similar. Java script was developed by Netscape. Microsoft reverse engineered Javascript and called it JScript


3).How do we add JavaScript onto a web page?
Ans:-
There are serveral way for adding javascript on a web page but there are two way with is commonly userd by developers
If your script code is very short and only for single page then following ways is best
a)You can place <script type="text/javascript"> tag inside the <head> element. 
Code:
<head>
<title>Page Title</title>
<script language="JavaScript" type="text/javascript">
   var name = "Vikas Ahlawta"
   alert(name);
</script>
</head>
b).If your script code is very large then you can make a javascript file and add its path in the following way..
Code:
<head>
<title>Page Title</title>
<script type="text/javascript" src="myjavascript.js"></script>
</head>


4).Is JavaScript case sensitive?
Ans:-Yes!
A function getElementById is not the same as getElementbyID


5).What are the types used in JavaScript? 
Ans:-String, Number, Boolean, Function, Object, Null, Undefined.


6).What are the boolean operators sported by JavaScript?
And Operator: &&
Or Operator: ||
Not Operator: !


7).What is the difference between “==” and “===”?
Ans:-
“==” checks equality only, 
“===” checks for equality as well as the type.


8).How to access the value of a textbox using JavaScript?
Ans:-
ex:-
Code:
<!DOCTYPE html>
<html>
<body>
Full name: <input type="text" id="txtFullName" name="FirstName" value="Vikas Ahlawat">
</body>
</html>

There are following way to access the value of the above textbox
var name = document.getElementById('txtFullName').value;
alert(name);
or 
we can use the old way
document.forms[0].mybutton.
var name = document.forms[0].FirstName.value;
alert(name);
Note:- this uses the "name" attribute of the element to locate it.


9).What are the way of make comment in Javascript?
Ans:-
// is used for line comments
ex:- var x=10; //comment text

/*
*/ is used for block comments
ex:-
var x= 10; /* this is
block comment example.*/


10).How you will get the CheckBox status whether it is checked or not?
Ans:-
var status = document.getElementById('checkbox1').checked; 
alert(status); 
it will return true or false


11).How to create arrays in JavaScript? 
Ans:-
There are Two way dor create array in Javascript like other languages..
a) first way to create array
Declare Array:-
Code:
var names = new Array();
Add Elements in Array:-
names[0] = "Vikas";
names[1] = "Ashish";
names[2] = "Nikhil";

b) this is second way
var names = new Array("Vikas", "Ashish", "Nikhil");


12).If an array with name as "names" contain three elements then how you will print the third element of this array?
Ans:- Print third array element document.write(names[2]); 
Note:- array index start with 0


13).How do you submit a form using Javascript? 
Ans:-Use document.forms[0].submit();


14).What does isNaN function do? 
Ans:-
It Return true if the argument is not a number.
ex:-
Code:
document.write(isNaN("Hello")+ "<br>");
document.write(isNaN("2013/06/23")+ "<br>");
document.write(isNaN(123)+ "<br>");

output will be:-
true
true
false


15).What is the use of Math Object in Javascript?
Ans:-
The math object provides you properties and methods for mathematical constants and functions.
ex:-
Code:
var x = Math.PI; // Returns PI
var y = Math.sqrt(16); // Returns the square root of 16
var z = Math.sin(90);    Returns the sine of 90

16). What do you understand by this keyword in javascript? 
Ans:-In JavaScript the this is a context-pointer and not an object pointer. It gives you the top-most context that is placed on the stack. The following gives two different results (in the browser, where by-default the window object is the 0-level context):

Code:
var obj = { outerWidth : 20 };

function say() {
    alert(this.outerWidth);
}
say();//will alert window.outerWidth
say.apply(obj);//will alert obj.outerWidth


17).What does "1"+2+4 evaluate to? 
Ans:-Since 1 is a string, everything is a string, so the result is 124. 


18).What does 3+4+"7" evaluate to?
Ans:-Since 3 and 4 are integers, this is number arithmetic, since 7 is a string, it’s concatenation, so 77 is the result.


19).How do you change the style/class on any element using javascript?
Ans:-
Code:
document.getElementById(“myText”).style.fontSize = “10";
-or-
document.getElementById(“myText”).className = “anyclass”;


20).Does javascript support foreach loop?
Ans:- Yes, See example here http://jsfiddle.net/gpDWk/ 


21).What looping structures are there in JavaScript? 
Ans:-for, while, do-while loops


22).what is an object in JavaScript, give an example?
Ans:-
An object is just a container for a collection of named values

// Create the man object
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;


23).How you will add function as a property in a JavaScript object? Give example.
Ans:-
Code:
var man = new Object();
man.name = 'Vikas Ahlawat';
man.living = true;
man.age = 27;

man.getName = function() { return man.name;}
console.log(man.getName()); // Logs 'Vikas Ahlawat'.


24).What is the similarity between 1st and 2nd statement?
1st:- var myString = new String('male'); // An object.
2nd:- var myStringLiteral = 'male'; // Primitive string value, not an object.
Ans:- Both will call String() constructor function
you can confirm it by run the following statement
console.log(myString.constructor, myStringLiteral.constructor);


25).What will be the output of the following statements?
Code:
var myString = 'Vikas' // Create a primitive string object.
var myStringCopy = myString; // Copy its value into a new variable.
var myString = null; // Manipulate the value
console.log(myString, myStringCopy);
Ans:- // Logs 'null Vikas'


26).Consider the following statements and tell what would be the output of the logs statements?
var price1 = 10;
var price2 = 10;
var price3 = new Number('10'); // A complex numeric object because new was used.
console.log(price1 === price2); 
console.log(price1 === price3);
Ans:-
console.log(price1 === price2); // Logs true.
console.log(price1 === price3); /* Logs false because price3 contains a complex number object and price 1
is a primitive value. */


27).What would be the output of the following statements?
var object1 = { same: 'same' };
var object2 = { same: 'same' };
console.log(object1 === object2);
Ans:- // Logs false, JavaScipt does not care that they are identical and of the same object type.
When comparing complex objects, they are equal only when they reference the same
object (i.e. have the same address). Two variables containing identical objects are not
equal to each other since they do not actually point at the same object.


28).What would be the output of the following statements?
Code:
var object1 = { same: 'same' };
var object2 = object1;
console.log(object1 === object2);
Ans:- // Logs true


29).What is this?
var myArray = [[[]]];
Ans:- Three dimantional array


30).Name any two JavaScript functions which are used for convert nonnumeric values into numbers?
Ans:-
Number()
parseInt()
parseFloat()
Code:
var n1 = Number(“Hello world!”); //NaN
var n2 = Number(“”);             //0
var n3 = Number(“000010”);       //10
var n4 = Number(true);           //1
var n5 = Number(NaN);            //NaN


31). What is the use of IsNan() function in JavaScript?
Ans:-isNaN() function accepts a single argument, which can be of any data type, to determine if the value is “not a number.”.
For more:-

Code:
alert(isNaN(“red”)); //true - cannot be converted to a number
alert(isNaN(true)); //false - can be converted to number 1
alert(isNaN(NaN)); //true
alert(isNaN(5)); //false - 5 is a number
alert(isNaN(“5”)); //false - can be converted to number 5


32). Can you describe "===" operator?
Ans:-
The identically equal operator is represented by three equal signs "===" and returns true only if the operands are equal without
conversion, as in this example

Code:
var result1 = (“55” == 55); //true - equal because of conversion
var result2 = (“55” === 55); //false - not equal because different data
types

33). DOM method "document.getElementById()" didn’t exist in Internet Explorer
prior to version 5. What is the way to detect that "document.getElementById()" is supported by the browser or not? 

Ans:-
if (document.getElementById){
return document.getElementById("txtBox1");
}
else {
throw new Error(“getElementById function not supported by browser”);
}





34). How do you check if a variable is an array in JavaScript?
Ans:- We can use "instanceof Array"
Example:-

Code:
if (v1 instanceof Array) {
alert('v1 is Array!');
} else {
alert('v1 is not an array');
}

35). What is the difference between following two
var myfunc = function() {}
function myfunc() {}

Ans:-
var myfunc = function() {} defines a variable that references an anonymous function.
function myfunc() {} defines a named function "myfunc".







Javascript - 4

Question 1: Scope

Consider the following code:
1
2
3
4
5
(function() {
   var a = b = 5;
})();
 
console.log(b);
What will be printed on the console?

Answer

The code above prints 5.
The trick of this question is that in the IIFE there are two assignments but the variable a is declared using the keyword var. What this means is that a is a local variable of the function. On the contrary, b is assigned to the global scope.
The other trick of this question is that it doesn’t use strict mode ('use strict';) inside the function. If strict mode was enabled, the code would raise the error Uncaught ReferenceError: b is not defined. Remember that strict mode requires you to explicitly reference to the global scope if this was the intended behavior. So, you should write:
1
2
3
4
5
6
(function() {
   'use strict';
   var a = window.b = 5;
})();
 
console.log(b);

Question 2: Create “native” methods

Define a repeatify function on the String object. The function accepts an integer that specifies how many times the string has to be repeated. The function returns the string repeated the number of times specified. For example:
1
console.log('hello'.repeatify(3));
Should print hellohellohello.

Answer

A possible implementation is shown below:
1
2
3
4
5
6
7
8
9
String.prototype.repeatify = String.prototype.repeatify || function(times) {
   var str = '';
 
   for (var i = 0; i < times; i++) {
      str += this;
   }
 
   return str;
};
The question tests the knowledge of the developer about inheritance in JavaScript and the prototypeproperty. It also verifies that the developer is able to extend native data type functionalities (although this should not be done).
Another important point here is to demonstrate that you are aware about how to not override possible already defined functions. This is done by testing that the function didn’t exist before defining your own:
1
String.prototype.repeatify = String.prototype.repeatify || function(times) {/* code here */};
This technique is particularly useful when you are asked to shim a JavaScript function.

Question 3: Hoisting

What’s the result of executing this code and why.
1
2
3
4
5
6
7
8
9
10
11
function test() {
   console.log(a);
   console.log(foo());
    
   var a = 1;
   function foo() {
      return 2;
   }
}
 
test();

Answer

The result of this code is undefined and 2.
The reason is that both variables and functions are hoisted (moved at the top of the function) but variables don’t retain any assigned value. So, at the time the variable a is printed, it exists in the function (it’s declared) but it’s still undefined. Stated in other words, the code above is equivalent to the following:
1
2
3
4
5
6
7
8
9
10
11
12
13
function test() {
   var a;
   function foo() {
      return 2;
   }
 
   console.log(a);
   console.log(foo());
    
   a = 1;
}
 
test();

Question 4: How this works in JavaScript

What is the result of the following code? Explain your answer.
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
var fullname = 'John Doe';
var obj = {
   fullname: 'Colin Ihrig',
   prop: {
      fullname: 'Aurelio De Rosa',
      getFullname: function() {
         return this.fullname;
      }
   }
};
 
console.log(obj.prop.getFullname());
 
var test = obj.prop.getFullname;
 
console.log(test());

Answer

The code prints Aurelio De Rosa and John Doe. The reason is that the context of a function, what is referred with the this keyword, in JavaScript depends on how a function is invoked, not how it’s defined.
In the first console.log() call, getFullname() is invoked as a function of the obj.prop object. So, the context refers to the latter and the function returns the fullname property of this object. On the contrary, when getFullname() is assigned to the test variable, the context refers to the global object (window). This happens because test is implicitly set as a property of the global object. For this reason, the function returns the value of a property called fullname of window, which in this case is the one the code set in the first line of the snippet.

Question 5: call() and apply()

Fix the previous question’s issue so that the last console.log() prints Aurelio De Rosa.

Answer

The issue can be fixed by forcing the context of the function using either the call() or the apply()function. If you don’t know them and their difference, I suggest you to read the article What’s the difference between function.call and function.apply?. In the code below I’ll use call() but in this case apply() would produce the same result:
1
console.log(test.call(obj.prop));