javascript-interview-questions (Part- 1)

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.

What are undeclared and undefined variables?
Undeclared variables are those that do not exist in a program and are not declared. If the program tries to read the value of an undeclared variable, then a runtime error is encountered.

Undefined variables are those that are declared in the program but have not been given any value. If the program tries to read the value of an undefined variable, an undefined value is returned.

Explain how can you submit a form using JavaScript?
To submit a form using JavaScript use document.form[0].submit();
document.form[0].submit();

Does JavaScript support automatic type conversion?
Yes JavaScript does support automatic type conversion, it is the common way of type conversion used by JavaScript developers

How can the style/class of an element be changed?

It can be done in the following way:
document.getElementById(“myText”).style.fontSize = “20?;
document.getElementById(“myText”).className = “anyclass”;

How can you convert the string of any base to integer in JavaScript?
The parseInt() function is used to convert numbers between different bases. parseInt() takes the string to be converted as its first parameter, and the second parameter is the base of the given string.

In order to convert 4F (of base 16) to integer, the code used will be –
parseInt ("4F", 16);

 What would be the result of 3+2+”7″?
Since 3 and 2 are integers, they will be added numerically. And since 7 is a string, its concatenation will be done. So the result would be 57.

What do mean by NULL in Javascript?
The NULL value is used to represent no value or no object.  It implies no object or null string, no valid boolean value, no number and no array object.

What are all the types of Pop up boxes available in JavaScript?
  • Alert
  • Confirm and
  • Prompt
What is the use of Void(0)?
Void(0) is used to prevent the page from refreshing and parameter “zero” is passed while calling.
Void(0) is used to call another method without refreshing the page. click here

What is the data type of variables of in JavaScript?
All variables in the JavaScript are object data types.

What are JavaScript Cookies?
Cookies are the small test files stored in a computer and it gets created when the user visits the websites to store information that they need. Example could be User Name details and shopping cart information from the previous visits.

What is break and continue statements?
Break statement exits from the current loop.
Continue statement continues with next statement of the loop.

What are the two basic groups of dataypes in JavaScript?
They are as –
  1. Primitive
  2. Reference types.
Primitive types are number and Boolean data types.
Reference types are more complex types like strings and dates.

Which keywords are used to handle exceptions?
Try… Catch—finally is used to handle exceptions in the JavaScript
    Try{
        //Code
    }
    Catch(exp){
        //Code to throw an exception
    }
    Finally{
        //Code runs either it finishes successfully or after catch
    }

Which keyword is used to print the text in the screen?
document.write(“Welcome”) is used to print the text – Welcome in the screen.

What is the use of Push method in JavaScript?
The push method is used to add or append one or more elements to the end of an Array. Using this method, we can append multiple elements by passing multiple arguments

What is the difference between JavaScript and Jscript?
Both are almost similar. JavaScript is developed by Netscape and Jscript was developed by Microsoft 

What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict Mode adds certain compulsions to JavaScript. Under the strict mode, JavaScript shows errors for a piece of codes, which did not show an error before, but might be problematic and potentially unsafe. Strict mode also solves some mistakes that hamper the JavaScript engines to work efficiently.

Strict mode can be enabled by adding the string literal “use strict” above the file. This can be illustrated by the given example:
function myfunction()
{
use strict";
var v = “This is a strict mode function";
}

What is the way to get the status of a CheckBox?
The status can be acquired as follows –
alert(document.getElementById(‘checkbox1′).checked);
If the CheckBox will be checked, this alert will return TRUE.

Explain window.onload and onDocumentReady?
The onload function is not run until all the information on the page is loaded. This leads to a substantial delay before any code is executed.

onDocumentReady loads the code just after the DOM is loaded. This allows early manipulation of the code.

 Describe the properties of an anonymous function in JavaScript?
A function that is declared without any named identifier is known as an anonymous function. In general, an anonymous function is inaccessible after its declaration.

Anonymous function declaration –
var anon = function() {
    alert('I am anonymous');
    };
    
    anon();

How are object properties assigned?
Assigning properties to objects is done in the same way as a value is assigned to a variable.
For example, a form object’s action value is assigned as ‘submit’ in the following manner – Document.form.action=”submit”

What is the role of break and continue statements?
Break statement is used to come out of the current loop while the continue statement continues the current loop with a new recurrence.

Example of terminating a loop using break 
<script>  
    for (i = 0i < 20i++) {  
        if (i >= 5) {  
            break;  
        }  
        document.write("Pass index " + i + " of the loop<br />");  
    }  
</script>  

output

JavaScript continue statement 
JavaScript continue statement is used to bypass the specified iterations of a loop, so that the code in the loop statement does not execute for the specified iterations and moves on to the next.
<script>  
    for (i = 0i < 20i++) {  
        if (i < 10) {  
            continue;  
        }  
        document.write("Pass index " + i + " of the loop<br />");  
    }  
</script>  

output

Explain Arrays in JavaScript.
 An array is a collection of the similar data types. All its values are stored in the index locations, which start in the range 0 to n-1.


Declaration of an Array
var myArray = [];  
var myArray = [value1value2value3so on...];  
var myArray = new myArray(length_of_array);  

Let's understand this with the following examples.

EXAMPLE: 1 
var myArray = [20304050];  
for (var i = 0i <= myArray.length - 1i++) {  
    document.write("The value at the index location " +i+" is "+myArray[i]+" <br/>");  
}  

The preceding code declares an array with 4 values. The for loop is used, which starts the index value "i" from 0 until the length of "myArray" and the index location is incremented by 1.

Exception Handling in JavaScript.
This is a new feature of JavaScript for handling the exceptions like in other programming languages, using try catch finally statements and the throw operator for handling the exceptions. Now, you can catch the runtime exception.
The following example shows an exception handling:

Example
<!DOCTYPE html>  
<html>  
<title>Article By Jeetendra</title>  
<head> </head>   
<body>  
    <script type="text/javascript">  
        document.write("Exception Handling in JavaScript</br>");  
  
        function ExceptHand() {  
            try {  
                alert("This is try block");  
                alert("Not present");  
            } catch (error) {  
                document.write(error);  
            }  
        }  
        ExceptHand();  
    </script>  
</body>  
</html>  

Closure in JavaScript
A closure is a function that remembers its outer variables and can access them.

Closures are one of the most powerful features of JavaScript. JavaScript allows for the nesting of functions and grants the inner function full access to all the variables and functions defined inside the outer function (and all other variables and functions that the outer function has access to). However, the outer function does not have access to the variables and functions defined inside the inner function. This provides a sort of security for the variables of the inner function. Also, since the inner function has access to the scope of the outer function, the variables and functions defined in the outer function will live longer than the outer function itself, if the inner function manages to survive beyond the life of the outer function. A closure is created when the inner function is somehow made available to any scope outside the outer function. See Examplehttps://www.w3schools.com

Example
<p>Counting with a local variable.</p>
<button type="button" onclick="myFunction()">Count!</button>
<p id="demo">0</p>

<script>
    var add = (function () {
    var counter = 0;
    return function () {counter += 1return counter;}
    })();

    function myFunction(){
    document.getElementById("demo").innerHTML = add();
    }
</script>

In the code above, the name variable of the outer function is accessible to the inner functions, and there is no other way to access the inner variables except through the inner functions. The inner variables of the inner function act as safe stores for the inner functions. They hold "persistent", yet secure, data for the inner functions to work with.

Chaining in JavaScript.
This technique got / retrieved popularity from jQuery. We write the series of statements, one after the other like a chain. 
$("#h1").text("Change text").css("color""red");   

What are Screen objects?
Screen objects are used to read the information from the client’s screen. The properties of screen objects are –

AvalHeight: Gives the height of client’s screen
AvailWidth: Gives the width of client’s screen.
ColorDepth: Gives the bit depth of images on the client’s screen
Height: Gives the total height of the client’s screen, including the taskbar
Width: Gives the total width of the client’s screen, including the taskbar

Define unescape() and escape() functions?
The escape () function is responsible for coding a string so as to make the transfer of the information from one computer to the other, across a network.

For Example:
<script>
document.write(escape(Hello? How are you!));
</script>

Output: Hello%3F%20How%20are%20you%21

The unescape() function is very important as it decodes the coded string.

It works in the following way.
For example:





<script>
document.write(unescape(Hello%3F%20How%20are%20you%21));
</script>

Output: Hello? How are you!

What are the decodeURI() and encodeURI()?
EncodeURl() is used to convert URL into their hex coding. And DecodeURI() is used to convert the encoded URL back to normal.
<script>
    var uri="my test.asp?name=ståle&car=saab";
    document.write(encodeURI(uri)+ "<br>");
    document.write(decodeURI(uri));
</script>

Output –
my%20test.asp?name=st%C3%A5le&car=saab
my test.asp?name=ståle&car=saab

What does the following statement declares?
var myArray = [[[]]];
It declares a three dimensional array.

Get all visible DIVs on a page with javascript?
It's easy with jQuery...
$("div:visible")

But if you want to be old school...
var divs = document.getElementsByTagName("DIV");
var elems = [];

for(var i = 0i < divs.lengthi++) {
  var div = divs[i];
  var vis = div.style.visibility;

  if(vis == 'block' || vis == 'inline')
    elems.push(div);
}

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.

Syntax: object.prototype.name=value
<script>
    function person(firstlastageeye) {
        this.firstName = first;
        this.lastName = last;
        this.age = age;
        this.eyeColor = eye;
    }
    person.prototype.nationality = "English";

    var myFather = new person("John""Doe"50"blue");
    document.getElementById("demo").innerHTML =
    "My father is " + myFather.nationality;
</script>

JSON.parse(): The JSON.parse() method parses a string as JSON

JSON parse example - Object From String
Create a JavaScript string containing JSON syntax:
var text = '{ "employees" : [' +
'{ "firstName":"John" , "lastName":"Doe" },' +
'{ "firstName":"Anna" , "lastName":"Smith" },' +
'{ "firstName":"Peter" , "lastName":"Jones" } ]}';

The JavaScript function JSON.parse(text) can be used to convert a JSON text into a JavaScript object:
var obj = JSON.parse(text);

Use the new JavaScript object in your page:
Example:
<p id="demo"></p>

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

JSON.stringify()
The JSON.stringify() method converts a JavaScript value to a JSON string.

What will the code below output to the console and why ?
console.log(1 +  "2" + "2");
console.log(1 +  +"2" + "2");
console.log(1 +  -"1" + "2");
console.log(+"1" +  "1" + "2");
console.log"A" - "B" + "2");
console.log"A" - "B" + 2);

The above code will output the following to the console:
"122"
"32"
"02"
"112"
"NaN2"
NaN
Here’s why…
The fundamental issue here is that JavaScript (ECMAScript) is a loosely typed language and it performs automatic type conversion on values to accommodate the operation being performed. Let’s see how this plays out with each of the above examples.

Example 1: 1 + "2" + "2" Outputs: "122" Explanation: The first operation to be performed in 1 + "2". Since one of the operands ("2") is a string, JavaScript assumes it needs to perform string concatenation and therefore converts the type of 1 to "1"1 + "2" yields "12". Then, "12" + "2" yields "122".
Example 2: 1 + +"2" + "2" Outputs: "32" Explanation: Based on order of operations, the first operation to be performed is +"2"(the extra + before the first "2" is treated as a unary operator). Thus, JavaScript converts the type of "2" to numeric and then applies the unary + sign to it (i.e., treats it as a positive number). As a result, the next operation is now 1 + 2 which of course yields 3. But then, we have an operation between a number and a string (i.e., 3 and "2"), so once again JavaScript converts the type of the numeric value to a string and performs string concatenation, yielding "32".
Example 3: 1 + -"1" + "2" Outputs: "02" Explanation: The explanation here is identical to the prior example, except the unary operator is - rather than +. So "1" becomes 1, which then becomes -1 when the - is applied, which is then added to 1yielding 0, which is then converted to a string and concatenated with the final "2" operand, yielding "02".
Example 4: +"1" + "1" + "2" Outputs: "112" Explanation: Although the first "1" operand is typecast to a numeric value based on the unary + operator that precedes it, it is then immediately converted back to a string when it is concatenated with the second "1" operand, which is then concatenated with the final "2" operand, yielding the string "112".
Example 5: "A" - "B" + "2" Outputs: "NaN2" Explanation: Since the - operator can not be applied to strings, and since neither "A" nor "B" can be converted to numeric values, "A" - "B" yields NaN which is then concatenated with the string "2" to yield “NaN2”.
Example 6: "A" - "B" + 2 Outputs: NaN Explanation: As exlained in the previous example, "A" - "B" yields NaN. But any operator applied to NaN with any other numeric operand will still yield NaN.

What will be the output of this code?
var x = 21;
var girl = function () {
    console.log(x);
    var x = 20;
};
girl ();
//Neither 21, nor 20, the result is undefined
It’s because JavaScript initialization is not hoisted.
(Why doesn’t it show the global value of 21? The reason is that when the function is executed, it checks that there’s a local x variable present but doesn’t yet declare it, so it won’t look for global one.)

What do the following lines output, and why?
console.log(1 < 2 < 3);
console.log(3 > 2 > 1);
The first statement returns true which is as expected. The second returns false because of how the engine works regarding operator associativity for < and >. It compares left to right, so 3 > 2 > 1 JavaScript translates to true > 1. true has value 1, so it then compares 1 > 1, which is false.
How do you add an element at the begining of an array? How do you add one at the end?
var myArray = ['a''b''c''d'];
myArray.push('end');
myArray.unshift('start');
console.log(myArray); // ["start", "a", "b", "c", "d", "end"]

Imagine you have this code:
var a = [123];
1) Will this result in a crash?
     a[10] = 99;

2) What will this output?
     console.log(a[6]);
  1. It will not crash. The JavaScript engine will make array slots 3 through 9 be “empty slots.”
  2.  Here, a[6] will output undefined, but the slot still remains empty rather than filled with undefined. This may be an important nuance in some cases. For example, when using map(), empty slots will remain empty in map()’s output, but undefined slots will be remapped using the function passed to it:
var b = [undefined];
b[2] = 1;
console.log(b);             // (3) [undefined, empty × 1, 1]
console.log(b.map(e => 7)); // (3) [7,empty × 1, 7]
What would following code return?
console.log(typeof typeof 1); // string
typeof 1 will return "number" and typeof "number" will return string.

What is the difference between undefined and not defined in JavaScript?
In JavaScript, if you try to use a variable that doesn't exist and has not been declared, then JavaScript will throw an error var name is not defined and script will stop executing.

Let's say var x is a declaration because you have not defined what value it holds yet, but you have declared its existence and the need for memory allocation.

var x// declaring x
console.log(x); //output: undefined

If a variable that is neither declared nor defined, when we try to reference such a variable we'd get the result not defined.
console.log(y);  // Output: ReferenceError: y is not defined

How can we empty the array below?
var arrayList = ['a','b','c','d','e','f'];

1- arrayList = []
2- arrayList.length = 0;
3- arrayList.splice(0, arrayList.length);
4-
while(arrayList.length){ arrayList.pop(); }

What will be the output of the code below?
var trees = ["xyz","xxxx","test","ryan","apple"];
delete trees[3];
console.log(trees.length);
The output would be 5. When we use the delete operator to delete an array element, the array length is not affected from this. This holds even if you deleted all elements of an array using the delete operator.

What will be the output of the code below?
var bar = true;
console.log(bar + 0);   
console.log(bar + "xyz");  
console.log(bar + true);  
console.log(bar + false);   

The code will output 1, "truexyz", 2, 1. Here's a general guideline for addition operators:
  • Number + Number -> Addition
  • Boolean + Number -> Addition
  • Number + String -> Concatenation
  • String + Boolean -> Concatenation
  • String + String -> Concatenation
Property flags and descriptors 
Object properties, besides a value, have three special attributes (so-called “flags”):
  1. writable – if true, the value can be changed, otherwise it’s read-only.
  2. enumerable – if true, then listed in loops, otherwise not listed.
  3. configurable – if true, the property can be deleted and these attributes can be modified, otherwise not.
We didn’t see them yet, because generally they do not show up. When we create a property “the usual way”, all of them are true. But we also can change them anytime. https://javascript.info

First, let’s see how to get those flags.
The method Object.getOwnPropertyDescriptor allows to query the full information about a property.
To change the flags, we can use Object.defineProperty.

"use strict";
var obj= {};
obj.name='suraj';

//Object.getOwnPropertyDescriptor allows to query the full information about a property.
let descriptor = Object.getOwnPropertyDescriptor(obj'name');
console.log(JSON.stringify(descriptornull2 ));

//To change the flags, we can use Object.defineProperty.
Object.defineProperty(obj"name", {
  value: "John"
});
descriptor = Object.getOwnPropertyDescriptor(obj'name');
console.log(JSON.stringify(descriptornull2 ));

Object.defineProperty(obj"name", {
  writable: false
});
debugger;
obj.name = "Pete"// Error: Cannot assign to read only property 'name'
Output:







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