Wednesday, February 28, 2018

Java script tricky questions and answers part II

1. What is the value of  "10"+3+4+3

Answer : "10343"

Explanation:
                  Because of first one "10" identified as string. So remaining also could be identified as string only.

Things To Remember:
                  First character is the matter here. If first one is string remaining will consider as string only.




2. Output of the below and explain why ?


var output = (function(x){
    delete x;
    return x;
  })(0);
  
  console.log(output);

Answer : 0.

Explanation: 
                 Delete operator will delete properties from an object. Here x mentioned as local variable.

Things To Remember:
                 Delete operator will not affect local variable.




3. Output of the below and explain why ?


var letters = ["A","B","C","D","E"];
delete letters[3];
  
  console.log(letters.length);

Answer: 5

Explanation:

                  When you delete an elements from an array by using delete operator, the length will not get affect.

Things To Remember:

                 The deleted value will be replaced by undefined and length will not get change.





4. Check below code and tell what is the output ?


console.log(false == '0')
console.log(false === '0')

Answer: true
               false

Explanation:
         
                 Here == and === doing the magic here. This is what, why we need to use always === if you want check equal value please do check its type also.

Things To Remember:

                 Always use === to check value and its type.




5. Explain below code output and why ?

(function(x) {
    return (function(y) {
        console.log(x);
    })(2)
})(1);

Answer: 1

Explanation :

                 Closure is the reason here, why its printing number 1 as output. Here x is defined outside of the inner function and closure have capability to get those value. So printing no 1 as output.

Things To Remember:

                  Closure function.




6. Check below code snippet and explain why ?

console.log(1 < 2 < 3);
console.log(3 > 2 > 1);

Answer: true
               false

Explanation:

                We can analyse the second log message why its return false. Then you can go ahead to compare first one why its returning true.

3>2 will return true. After that, we know true can consider as 1. So now 1>1 which could return false.

Things To Remember:

True can consider as 1 too.




7. Below code is consider as number or string or any other type ?

console.log(+'dude');

Answer: NaN

Explanation:

                Because of + symbol compiler will consider as adding operation (unary operator) so it will take dude as a number and trying to add. But It can not. So telling NaN.

Things To Remember:

                 First character is the matter here.




8. Explain following code result.

var test = "testingHoist";

 (function () {
     console.log("The value is " + test);

     var test = "testingHoistXXXXXXX";

     console.log("Latest value is " + test);
})();

Answer: The value is undefined
               Latest value is testingHoistXXXXXXX

Explanation:
       
               Because of hoist these results we got undefined.

Things To Remember:
   
                Functions and variables are hoisted in java script.




9. Check the below code and explain why?
               

var testObject = {
    foo: "bar",
    func: function() {
        var self = this;
        console.log("outer func first:  this.foo = " + this.foo);
        console.log("outer func second:  self.foo = " + self.foo);
        (function() {
            console.log("inner func first:  this.foo = " + this.foo);
            console.log("inner func second:  self.foo = " + self.foo);
        }());
    }
};
testObject.func();

Answer: outer func first:  this.foo = bar
               outer func second:  self.foo = bar
               inner func first:  this.foo = undefined
               inner func second:  self.foo = bar

Explanation :

               Because of "this" keyword we are getting this output. You should always assign this to self like above. So that you can access outer variables. But if you know ES6 arrow function you no need to worry about this.

Things To Remember:

               You should always assign to self (this=self) in ES5, so that you can access varibles. But ES6 solved this problem.





10. Explain below code

console.log(0.5 + 0.3);
console.log(0.4 + 0.2 == 0.6);

Answer: 0.8
               false

Explanation :

               Dont expect always it return the correct sum value and true. Java script would consider this as floating point precision , so it may tend to provide any wrong results.

Things To Remember:

               For this type of calculation work, please go with Math.So that it will solve your problem.






Tuesday, February 27, 2018

Important java script interview Questions and answers - Part I

1. What is JavaScript?

JavaScript is a client-side as well as server side scripting language. JavaScript is also an Object based Programming language.

2. What are JavaScript types?

Null
Undefined
Boolean
Number
String
Object

3. What is Difference between = = and = = = ?

= = Operator check the equality of value on both side.

= = = Operator check the equality of value both side as well as its type too.

var num = 1;
  var str = "1";
  console.log(num == str); //Output: TRUE

var num = 1;
  var str = "1";
  console.log(num === str); //Output: FALSE

4. How do you access object property?

By using dot . operator

var obj1 = {name: 'Test'};
  obj1.name; //Output: Test

5. What is hoisting ?

Suppose If developer forgot to declare a variable and he/she directly try to use it then java script engine declare it one level up. So the leveled up variable will become a global.

Lifting variable declaration one level up is called hoisting.
The below example can explain clearly.

function person(){
   name = 'john'; //Directly using without declaring
  }

The above example will not any error because It will make var name(global) internally.

6. What is callback function ?

Callback function is a function which is passed to another function as a parameter and callback function is called inside the other function.

It also known as a higher-order function.

See the below example.


function doTest(test, callback) {
  alert('Checking ${test}');
  callback();
}

doTest('test', function() {
  alert('Finished...');
});

7. What is this keyword ?

Just its expressing context of current object. By using "this" you can access the current object.

8. What are the types of functions available in java script ?
       1. Named Function
       2. Anonymous Function
       3. Self-invoking Function

9. Give me an example for Named function ?

A function with a name is called named function.

example below,

function person(){ //Some code here  }

10. What is isNaN function in java script?

If the specified argument is not a number then it will return true otherwise it is false.

11. How can you submit a form in java script?

Use the below code to submit a form.


document.form[0].submit();

Note : form[0] mentioned order of form number.

12. What is an undefined?

Undefined may exists by following the below scenario,

1. You are using variable and Its not exist in the code.
2. Property itself not exist
3. Variable is not assigned properly(means no value assigned).

13. Break and continue statements difference?

Break  - It exits from the current loop.
Continue - It continues to the next iteration of the loop.

14. What is self invoking function ?

Self invoking function is a function which can run by itself when encountered and we no need to call.

Below is without arguments,
(function(){
  alert("test");
  })();
  

Below is passing arguments,


(function(name){
  alert(name);
  })("test");

15. What is anonymous function ?

Anonymous function a function which do not have any name.


var test = function(){
   //some code here
  }

Note: Don't confuse here, just we are assigning to variable called test. But function not having any name.





Monday, February 26, 2018

Java main method interview questions and answers

1. Can I write java program without String args[] in main method ?

If you write java program without String args [] like below

public static void main (){
//Some code
}

The code will run. But JVM Can not recognize main method since it will always check main method string array parameter.

2. Difference between System.exit(0) and System.exit(1) ?

Sytem.exit(0) normally terminates the program. System.exit(1) also terminates the program, because It could find some error.

3. Is it possible to call main() from another class ?

Yes, Its possible by calling like Classname.main(). Note here, you should pass string array since main method will expect string array.

4. Can I overload main method ?

public class MainMethodOverloadExample
{
    public static void main(String[] args)
    {
        System.out.println("Execution will be started here");
    }
 
    void main(int args)
    {
        System.out.println("Overloaded main method I");
    }
 
    double main(int i, double d)
    {
        System.out.println("Overloaded main method II");
        //Some code here
    }
}

5. Is it possible change main method access modifier except public ?

No, main() method must be public. Your code will get compile.But Run time Error will happen when you try to run. Because JVM unable to access main method.

6. Can main() method take an argument other than string array?

No, argument of main() method must be string array

7. Can I change main() method to non static ?

No, main() method must be declared as static so that JVM can find and call main() method without instantiating it’s class. Compilation will be successful but program fails at run time.

8.Can we override main method in Java ?

No, you can not override main method in Java, Because main is static method and you can not override static method in Java.

9. Can we make main final in Java?

The Code will compile without any problems but it will throw a run-time exception saying "main method not public".

10. Can we make main method as synchronized in Java?

Yes, main can be synchronized in Java,  synchronized modifier is allowed in main signature.







Thursday, February 22, 2018

Check Date within Date Range

Here the way you can compare one date between two dates in java script.

Date format here is like YYYY-MMM-DD (2015-Sep-12)


if(dateCheck("2012-Sep-12","2017-Jan-14","2012-Sep-11"))
    alert("Ok Match");
else
    alert("Not Match");

function dateCheck(from,to,check) {

    var fDate,lDate,cDate;
    
    fDate = Date.parse(from);
    lDate = Date.parse(to);
    cDate = Date.parse(check);
    
    if((cDate <= lDate && cDate >= fDate)) {
        return true;
    }
    return false;
}

The below one if you have different time format you Date constructor and achieve the above task.
Date format is like YYYY-MM-DD (2018-01-30). And remember for month you should subtract it from one. I mean month-1. Since month starting from number 0.

var parts1 = from.split('-');
    var parts2 = to.split('-');
    var parts3 = check.split('-');
    
    fDate = new Date(parts1[0], parts1[1] - 1, parts1[2]); 
    lDate = new Date(parts2[0], parts2[1] - 1, parts2[2]); 
    cDate = new Date(parts3[0], parts3[1] - 1, parts3[2]);

 console.log("From Date " + fDate.toDateString());
    console.log("Last Date " + lDate.toDateString());
    console.log("Check Date " + cDate.toDateString());