javascript-interview-questions (Part- 2)

What is JavaScript?
The JavaScript is most popular scripting languages and it developed by Netscape and used to develop the client side web applications.

Is JavaScript Case Sensitive?
Yes! JavaScript is a case sensitive because a function “str” is not equal to “Str”.

What Is the Type of JavaScript?
There are different of Type as given below.
  1. String, 
  2. Number,
  3. Boolean,
  4. Function,
  5. Object,
  6. Null,
  7. Undefined.
What Types of Boolean Operators in JavaScript?
There are three types of Boolean operators as given below.
1.      AND (&&) operator, 
2.      OR (||) operator and 
3.      NOT (!) Operator

What Is the difference Between “==” and “===”?
The double equal “==” is an auto-type conversion and it checks only value not type.
The three equal “===” is not auto-type conversion and it check value and type both.

The example looks like–
if(1 == "1")
//Its returns true because it's an auto-type conversion and it checks only value not type.

if(1 === "1")//Its returns false because it's not auto-type conversion and it check value and type both.

if(1=== parseInt("1"))// its returns true.
// alert(0 == false); // return true, because both are same type.
// alert(0 === false); // return false, because both are of a different type.
// alert(1 == "1"); // return true, automatic type conversion for value only.
// alert(1 === "1"); // return false, because both are of a different type.
// alert(null == undefined); // return true.
// alert(null === undefined); // return false.
// alert('0' == false); // return true.
// alert('0' === false); // return false.
// alert(1=== parseInt("1")); // return true.   

What Is an Object?
The object is a collection of properties and the each property associated with the name-value pairs. The object can contain any data types (numbers, arrays, object etc.)

The example as given below –
var myObject= {empId : “001”, empCode :X0091”};

In the above example, here are two properties one is empId and other is empCode and its values are “001” and “X0091”.
Types of creating an object
1.      Object literals
2.      Object constructor

Object Literals: This is the most common way to create the object with object literal and the example as given below.

The empty object initialized using object literal i.e.
var emptyObj = {};

This is an object with 4 items using object literal i.e.
var emptyObj ={
empId:Red”,
empCode: “X0091”,
empDetail : function(){
   alert(“Hi”);
  };
};

Object Constructor: The second way to create object using object constructor and the constructor is a function used to initialize new object. 

The example as given below -
var obj = new Object();
Obj.empId=”01”;
Obj.empCode=”S091”;

Obj.empAddressDetai = function(){
console.log(“HiI am Suraj”);
};

What Is Scope Variable in JavaScript?
The scope is set of objects, variables and function and the JavaScript can have global scope variable and local scope variable.

The global scope is a window object and it’s used out of function and within the functions.
The local scope is a function object and it’s used within the functions.

The example for global scope variable -
var gblVar = "Suraj";

function getDetail() {
     console.log(gblVar);
}

And other example for global -
function demoTest() {
      x = 20;
};
console.log(x); //output is 20

The example for local scope variable -
function getDetail() {
     var lclVar = "Suraj K";
     console.log(lclVar );
}

And other example for local -
function demoText() {
    var x = 15;
};
console.log(x); //undefined

What Is an Associative Array in JavaScript?

The array with name indexes are called associative array and the associative array is provide a ways to store the information.

How To Achieve Inheritance in JavaScript?

What Is typeof Operator?
The typeof operator is used to find the type of variables.

The example as given below -
typeof "Anil Singh"   // Returns string
typeof 3.33           // Returns number
typeof true          // Returns Boolean
typeof { name: 'Anil'age: 30 } // Returns object
typeof [10203040// Returns object

What Is a Public, Private member in Javascript.
Fist I am creating a constructor class and trying to achieve the public and private variables and detail as given below –

function myEmpConsepts() { // This myEmpConsepts is a constructor  function.
var empId = "00201"//This is a private variable.
this.empName = "Suraj K"//This is a public variable.

this.getEmpSalary = function () {  //This is a public method
console.log("The getEmpSalary method is a public method")
}
}

//This is an instance method and its call at the only one time when the call is instantiate.
myEmpConsepts.prototype.empPublicDetail = function () {
console.log("I am calling public vaiable in the istance method :" + this.empName);
console.log("I am calling private vaiable in the istance method :" + this.empId);
}

var _objnew myEmpConsepts();
_obj.empPublicDetail();


Output:
I am calling public vaiable in the istance method : Suraj K
I am calling private vaiable in the istance method : undefined

How to Add/Remove Properties to Object in run-time in JavaScript?
I am going to explain by example for add and remove properties from JavaScript objects as give below.

//This is the JSON object.
var objectJSON = {
    id: 1,
    name: "Anil Singh",
    dept: "IT"
    };

This example for add property -
//This is used to add the property.
objectJSON.age = 30;
console.log(objectJSON.age); //The result is 30;

//This is the JSON object.
var objectJSON = {
    id: 1,
    name: "Anil Singh",
    dept: "IT",
    age: 30
    };

This example for delete property -
//This is the process to delete
delete objectJSON.dept;

Why Never Use New Array in JavaScript?

We have some fundamental issues with new Array () the example in detail for array constructor function as given below.

When Array Have more the one Integer?
var newArray = new Array(1020304050);
console.log(newArray[0]); //returns 10.
console.log(newArray.length); //returns 5.

When Array Have Only One Integer?
var newArray = new Array(10);
console.log(newArray[0]); //returns undefined

//returns 10 because it has an error "array index out of bound";
console.log(newArray.length); 

//This is the fundamental deference to need to avoid the new array ();

What is eval() and floor() functions in JavaScript?
The eval() function used in execute an argument as expression or we can say that evaluate a string as expression and it used to parse the JSON.

The example over eval() function as given below -
var x = 14;
eval('x + 10'); //The output is 24.

Another over eval() function example -
eval('var myEval = 10');
console.log(myEval); // The output is 10.

The floor () function is a static method of Math and we can write as Math.floor() and used to round the number of downwards i.e.

Math.floor(1.6);//The output is 1.

What is join() and isNaN() functions in JavaScript?
The is join() function used to join the separator in the array.

Syntax - 
myArray.join(mySeparator);

The example as given below -
var alfabets = ["A""B""C""D"];
//Join without seperator
var result1 = alfabets.join();//The output is A B C D.
//Join with seperator.
var result2 = alfabets.join(','); //The output is A, B, C, D.

The isNaN() function is used to check the value is not-a-number.

The example as given below -
var var1 = isNaN(-1.23);//The output is false.
var var2 = isNaN(3);//The output is false.
var var3 = isNaN(0);//The output is false.
var var3 = isNaN("10/03/1984"); //The output is true.

What Is Function Overloading in JavaScript?
There is no real function overloading in JavaScript and it allows passing any number of parameters of any type.

You have to check inside the function how many arguments have been passed and what is the type arguments using typeof.

The example for function overloading not supporting in JavaScript as gives below -
function sum(ab) {
    alert(a + b);
}
function sum(c) {
    alert(c);
}
sum(3);//The output is 3.
sum(24);//The output is 2.


In the JavaScript, when we write more than one functions with same name that time JavaScript consider the last define function and override the previous functions. You can see the above example output for the same.

What Is Prototype in JavaScript?
Every JavaScript object has a prototype. The prototype is also an object. All JavaScript objects inherit their properties and methods from their prototype.
The prototype property allows you to add properties and methods to an object.

The example without prototype as given below -
var employee = function () {
//This is a constructor function.
}

//Crate the instance of above constructor function and assign in a variable
var empInstance = new employee();
empInstance.deportment = "IT";

console.log(empInstance.deportment);//The output of above is IT.

//The example with prototype as given below-
var employee = function () { //This is a constructor  function.
}

employee.prototype.deportment = "IT";//Now, for every instance employee will have a deportment.

//Crate the instance of above constructor functions and assign in a variable
var empInstance = new employee();
empInstance.deportment = "HR";

console.log(empInstance.deportment);//The output of above is IT not HR.


What will be output of below code:

var x = "5" + 2 + 3;
//Output= 523

var x = 2 + 3 + "5";
//Output= 55

var $ = 2;
var $myMoney = 5;
console.log($ + $myMoney);
//Output= 7


JavaScript Data Types
JavaScript variables can hold many data types: numbers, strings, objects and more:

var length = 16;                               // Number
var lastName = "Johnson";                      // String
var x = {firstName:"John"lastName:"Doe"};    // Object

JavaScript Types are Dynamic
JavaScript has dynamic types. This means that the same variable can be used to hold different data types:

var x;           // Now x is undefined
x = 5;           // Now x is a Number
x = "John";      // Now x is a String

In JavaScript, a variable without a value, has the value undefined. The type is also undefined.

var car;    // Value is undefined, type is undefined
var car = "";    // The value is "", the typeof is "string"

In JavaScript null is "nothing". It is supposed to be something that doesn't exist.

Unfortunately, in JavaScript, the data type of null is an object.                       

Difference Between Undefined and Null
undefined and null are equal in value but different in type:

typeof undefined           // undefined
typeof null                // object

null === undefined         // false
null == undefined          // true

The JavaScript this Keyword 
The JavaScript this keyword refers to the object it belongs to.

It has different values depending on where it is used:
  1. In a method, this refers to the owner object.
  2. Alone, this refers to the global object.
  3. In a function, this refers to the global object.
  4. In a function, in strict mode, this is undefined.
  5. In an event, this refers to the element that received the event.
  6. Methods like call(), and apply() can refer this to any object.
// Create an object:
var person = {
    firstName: "John",
    lastName : "Doe",
    id     : 5566,
    fullName : function() {
      return this.firstName + " " + this.lastName;
    }
  };
  
  // Display data from the object:
  document.getElementById("demo").innerHTML = person.fullName();


In the  above example, this represents the person object. https://www.w3schools.comhttps://www.geeksforgeeks.org

The indexOf() method returns the position of the first occurrence of a specified text. The indexOf() method accepts a second parameter as the starting position for the search.
The search() method returns the position of the first occurrence of a specified text in a string

var str = "Please locate where 'locate' occurs!";
var pos = str.indexOf("locate"); //str.indexOf("locate",15);
var pos2 = str.search("locate");
console.log(pos);
console.log(pos2);
Output: 7,7

var x = 10;
var y = 20;
console.log("The result is: " + x + y);
Output: The result is: 1020

var x = 10;
var y = 20;
var z = "30";
var result = x + y + z;
console.log(result);
Output: 3030

Note: The JavaScript interpreter works from left to right. First 10 + 20 is added because x and y are both numbers. Then 30 + "30" is concatenated because z is a string.

JavaScript will try to convert strings to numbers when dividing and multiplying, subtracting.
var x = "100";
var y = "10";
console.log(x + y); //10010
console.log(x - y); //90
console.log(x * y); //1000
console.log(x / y); //10

//A number divided by a non-numeric string becomes NaN (Not a Number)
console.log(100 / "Apple");

//A number divided by a numeric string becomes a number
console.log(100 / "10");
Output: NaN
             10

You can use the global JavaScript function isNaN() to find out if a value is a number
var x = 100 / "Apple";
console.log(isNaN(x));
Output: true

var x = NaN;
var y = 5;
console.log(x+y);
Output: NaN

var x = NaN;
var y = "5";
console.log(x + y); 
Output: NaN5

NaN is a number: typeof NaN returns number:
var x = NaN;
console.log(typeof x);
Output: number

Arrays are a special type of objects. The typeof operator in JavaScript returns "object" for arrays.
var cars = new Array("Saab""Volvo""BMW");
var cars2 = ["Saab""Volvo""BMW"];
console.log(cars); 
console.log(cars[0]); 
Output: Saab,Volvo,BMW
             Saab

var cars = new Array("Saab""Volvo""BMW");

// The length property returns the number of elements
var x = cars.length; //Output: 3

// The sort() method sorts arrays
var y = cars.sort();   


The best way to loop through an array is using a standard for loop

var fruits = ["Banana""Orange""Apple""Mango"];
for (var i = 0i < fruits.lengthi++) {
  console.log(fruits[i]);
}


// Adding Array Elements
fruits.push("Lemon");
fruits[fruits.length] = "Lemon"

The Difference Between Arrays and Objects
  • In JavaScript, arrays use numbered indexes.  
  • In JavaScript, objects use named indexes.
Avoid new Array()
These two different statements both create a new empty array named points:
var points = new Array();     // Bad
var points = [];              // Good 

The new keyword only complicates the code. It can also produce some unexpected results:

// Creates an array with two elements (40 and 100)
var points = new Array(40100);  

// Creates an array with 40 undefined elements !!!!!
var points = new Array(40);  

How to Recognize an Array
The problem is that the JavaScript operator typeof returns "object":
To solve this problem ECMAScript 5 defines a new method Array.isArray():
Array.isArray(fruits);   // returns true

The pop() method removes the last element from an array.
The push() method adds a new element to an array (at the end).
The shift() method removes the first array element and "shifts" all other elements to a lower index. Shifting is equivalent to popping, working on the first element instead of the last.
The unshift() method adds a new element to an array (at the beginning), and "unshifts" older elements.
Using delete may leave undefined holes in the array. Use pop() or shift() instead.
you can use splice() to remove elements without leaving "holes" in the array

var fruits = ["Banana""Orange""Apple""Mango"];

 // Removes the last element ("Mango") from fruits
fruits.pop();         

//  Adds a new element ("Kiwi") to fruits
fruits.push("Kiwi");       

// Removes the first element "Banana" from fruits
fruits.shift();    

// Adds a new element "Lemon" to fruits
fruits.unshift("Lemon");    

// Changes the first element in fruits to undefined
delete fruits[0];   

// Removes the first element of fruits
fruits.splice(01);

The sort() method sorts an array alphabetically. https://www.w3schools.com
Understanding the Sort Method of Arrays https://betterprogramming.pub/understanding-the-sort

var fruits = ["Banana""Orange""Apple""Mango"];
// First sort the array
fruits.sort();
// Then reverse it:
fruits.reverse();

console.log(fruits);
Output: Orange,Mango,Banana,Apple

By default, the sort() function sorts values as strings. But what if we have array of number type?
var points = [40100152510];

//You can fix this by providing a compare function
points.sort(function(ab){return a - b});

//Use the same trick to sort an array descending:
//points.sort(function(a, b){return b - a});
console.log(points);

Output: 1,5,10,25,40,100

Array.filter()
Creates a new array with all array elements that passes a test.

var numbers = [45491625];
var over18 = numbers.filter(myFunction);
console.log(over18);

function myFunction(valueindexarray) {
  return value > 18;
}
Output: 45, 25

Arrow function in JS
var hello;
hello = () => {
  return "Hello World!";
}

//without the brackets or the return keyword.
hello = () => "Hello World!";

//With parameter
hello = (val=> "Hello " + val;

//if you have only one parameter in an Arrow Function, you can skip the parentheses.
hello = val => "Hello " + val;

console.log(hello());
console.log(hello("Universe!"));


Output of below codes ?
console.log(10 + "5");  // Output: 105
console.log("10" + 5);   // Output: 105
console.log("10" + "5");   // Output: 105

console.log(typeof undefined);   //Output: undefined
console.log(typeof null );  //Output: Object

console.log(100 / "Apple");    // Output: NaN
console.log(100 / "10");    // Output: 10


var a = 5;  
console.log("a is " + a + " and b is " + b); 
//Output: a is 5 and b is undefined
var b = 7;  

var c = 5
var d;     
console.log(c + " " + d);
//Output: 5 undefined
d = 7

Memory Management in Javascript
JavaScript automatically allocates memory when values are initially declared or objects are created and frees it when they are not used anymore (garbage collection)

JavaScript, utilize a form of automatic memory management known as garbage collection (GC). The purpose of a garbage collector is to monitor memory allocation and determine when a block of allocated memory is no longer needed and reclaim it. 

Errors & Exceptions Handling in Javascript
  • The try...catch...finally Statement
  • The onerror() Method
The onerror event handler was the first feature to facilitate error handling in JavaScript. The error event is fired on the window object whenever an exception occurs on the page.

The onerror event handler provides three pieces of information to identify the exact nature of the error −
  1. Error message − The same message that the browser would display for the given error
  2. URL − The file in which the error occurred
  3. Line number− The line number in the given URL that caused the error
      <script type = "text/javascript">
         <!--
            window.onerror = function (msgurlline) {
               alert("Message : " + msg );
               alert("url : " + url );
               alert("Line number : " + line );
            }
         //-->
      </script>
      
      <form>
        <input type = "button" value = "Click Me" onclick = "myFunc();" />
      </form>

Here is the example to show how to extract this information.
You can use an onerror method, as shown below, to display an error message in case there is any problem in loading an image.

<img src="myimage.gif" onerror="alert('An error occurred loading the image.')" />

You can use onerror with many HTML tags to display appropriate messages in case of errors.

What is an event loop in JavaScript?
Browser JavaScript execution flow, as well as in Node.js, is based on an event loop.
The Event Loop has one simple job — to monitor the Call Stack and the Callback Queue. If the Call Stack is empty, the Event Loop will take the first event from the queue and will push it to the Call Stack, which effectively runs it. Such an iteration is called a tick in the Event Loop. click here



0 comments:

Post a Comment

Topics

ADFS (1) ADO .Net (1) Ajax (1) Angular (43) Angular Js (15) ASP .Net (14) Authentication (4) Azure (3) Breeze.js (1) C# (47) CD (1) CI (2) CloudComputing (2) Coding (7) CQRS (1) CSS (2) Design_Pattern (6) DevOps (4) DI (3) Dotnet (8) DotnetCore (16) Entity Framework (2) ExpressJS (4) Html (4) IIS (1) Javascript (17) Jquery (8) Lamda (3) Linq (11) microservice (3) Mongodb (1) MVC (46) NodeJS (8) React (11) SDLC (1) Sql Server (32) SSIS (3) SSO (1) TypeScript (1) UI (1) UnitTest (1) WCF (14) Web Api (15) Web Service (1) XMl (1)

Dotnet Guru Archives