Showing posts with label Java script interview questions. Show all posts
Showing posts with label Java script interview questions. Show all posts

Friday, March 30, 2018

Array slice method


The syntax is:

arr.slice(start, end)

Slice method will returns a new array where it copies all items metioned from start index "start" to "end".

Both start and end can be negative, in this case position from array end is assumed.(like splice).

Below example can illustrate more...



let str = "test";
let arr = ["t", "e", "s", "t"];

alert( str.slice(1, 3) ); // es
alert( arr.slice(1, 3) ); // e,s

alert( str.slice(-2) ); // st
alert( arr.slice(-2) ); // s,t


Things To Remember:

1. Remembering the syntax make you more stronger easily in javascript.

2. Slice end will not be added while slice operation.

3. Slice will return an array always.

4. Negative index position allowed.







Array methods splice in detail


We have already seen some array methods, now we can see some other important methods.

The syntax of splice method is,

arr.splice(index[, deleteCount, elem1, ..., elemN])

index - specifying the position.

deleteCount - specifying the count of deleted elements.( don't confuse, we can see example)


1. First let start with deletion, see below example.



let arrTest = ["I", "study", "JavaScript"]; // Index start from 0

arrTest.splice(1, 1); // from index 1 remove 1(deletedcount) element

alert( arrTest ); // ["I", "JavaScript"]



2. Remove and Replace with other elements.


let spliceTest = ["I", "study", "JavaScript", "right", "now"];

spliceTest.splice(0, 3, "Let's", "dance"); // 0 is index;
                             3 - delete count ; 
                             remaining is for insert element

alert( spliceTest ) //  ["Let's", "dance", "right", "now"]


3. How to store removed array elements ?


let normalArray = ["I", "study", "JavaScript", "right", "now"];

// remove 2 first elements
let removedArrayElement = normalArray.splice(0, 2);

alert( removedArrayElement ); // "I", "study" <-- removed elements from an array

3. I do not want to remove an elements, but I need to insert with splice. How ?



let Originalarr = ["I", "study", "JavaScript"];

// from index 2
// delete 0 --> This is important point here
// then insert "complex" and "language"
Originalarr.splice(2, 0, "complex", "language");

alert( Originalarr ); // "I", "study", "complex", "language", "JavaScript"


4. Can I go ahead with negative indexes ?

Negative indexes are allowed in splice. It specify the position from the end of the array.

-1 means, one step back from end
-2 means, two step back from end and so on....


Example is below...



let arrNegativeEg = [1, 2, 5];

// from index -2 (two step from the end)
// delete 0 elements,
// then insert 3 and 4
arrNegativeEg.splice(-2, 0, 3, 4);

alert( arrNegativeEg ); // 1,3,4,2,5








Array with loop

Some types of for loop is there to iterate an array element. Let see one by one.

1. Classical for loop

2. for..of loop

3. for..in loop


Example for classical for loop.


let arrayExampleLoop = ["Apple", "Orange", "Pear"];

for (let i = 0; i < arr.length; i++) {
  alert( arrayExampleLoop[i] );
}


 Example for for..of loop:


let fruitsForOfLoop = ["Apple", "Orange", "Plum"];

// iterates over array elements
for (let fruit of fruitsForOfLoop) {
  alert( fruit );
}


Example for for...in loop:



let arrForInLoop = ["Apple", "Orange", "Pear"];

for (let key in arrForInLoop) {
  alert( arrForInLoop[key] ); // Apple, Orange, Pear
}

For arrays , we should not use for..in loop(performance issue) . But for objects you can go.








Sunday, March 4, 2018

Difference between let const and var

There are three types of variable declaration is possible in ES6. Each have some different scope so developer should use that correct situation.


1. Variable by using var

Before Es6 came , var was used at all time. But after ES6 , developer have choose let. However, still developers are using both let and var.

Simple example, var name="test";

Remember, let and var have huge difference there.

See the below example,

(function (){
  for(var i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

console.log(i); // Print 10

From the above code loop running and printing value 0, 1, 2... 9. But after that it will print 10 also. Because still variable i have scope. But if you use let here instead of var, it will error.


2. Variable by using let

Use let keyword to create variable. Its a block level scope.

Example:

let message;                 // Just declaration using let
message = 'Hello!';
let name = 'John', age = 19; //multiple variables
alert(message); // alert show message value


let- block level scope
Example below,


(function (){
  for(let i = 0; i<10; i++) {
    console.log(i)
  }
})(); // Print 0 to 9

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

Hope now you have understand var and let difference.

3. Variable by using const

If you want any variable should be constant, go for this. Once assigned, we can not reassign.

Example :


const FixedValue =10;
  console.log(FixedValue);  //Print 10
  FixedValue =20;           //throws Error
  console.log(FixedValue); 

Above code, FixedValue assigned already and trying to reassign throwing an error.



Conclusion:

So based on your situation scope level choose the right one. Better one is let than var and const will be choose for constant.









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.