1. What are the different data types in JavaScript?
JavaScript has six primitive data types: undefined, null, boolean, number, string, and symbol. It also has one non-primitive data type, which is object.
2. What is the difference between undefined and null in JavaScript?
Undefined represents a variable that has been declared but has not been assigned a value, whereas null represents a variable that is explicitly assigned a value of null, indicating the absence of any object value.
3. What is the use of ‘use strict’ in JavaScript?
‘use strict’ is a directive that enables strict mode in JavaScript. It helps in writing more reliable and error-free code by enforcing stricter parsing and error handling rules.
4. What is hoisting in JavaScript?
Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their containing scope during the compilation phase, allowing them to be used before they are declared.
5. What is the ‘this’ keyword in JavaScript?
The ‘this’ keyword refers to the context within which a function is executed. Its value is determined by how a function is invoked.
6. What are closures in JavaScript?
Closures are functions that have access to variables from an outer function that has already returned. They retain access to those variables even after the outer function has finished executing.
7. What is the difference between ‘==’ and ‘===’ operators in JavaScript?
‘==’ is an equality operator that performs type coercion, whereas ‘===’ is a strict equality operator that does not perform type coercion. ‘===’ checks for equality of both value and type.
8. How can you check if a variable is an array in JavaScript?
You can use the Array.isArray() method to check if a variable is an array. For example:
if (Array.isArray(myVariable)) {
// It is an array
}
9. What is event delegation in JavaScript?
Event delegation is a technique in which you attach a single event listener to a parent element instead of attaching multiple event listeners to individual child elements. The events are then handled based on the target element that triggered the event.
10. What is the difference between ‘null’ and ‘undefined’?
‘null’ is an assignment value that represents the absence of a value, whereas ‘undefined’ is a built-in value that indicates the absence of an assigned value. ‘null’ is an object type, while ‘undefined’ is of undefined type.
11. What are JavaScript promises?
Promises are objects used for asynchronous programming in JavaScript. They represent the eventual completion (or failure) of an asynchronous operation and allow handling the result asynchronously using callbacks.
12. Enumerate the differences between Java and JavaScript?
Java is a complete programming language. In contrast, JavaScript is a coded program that can be introduced to HTML pages. These two languages are not at all inter-dependent and are designed for different intent. Java is an object-oriented programming (OOPS) or structured programming languages like C++ or C, whereas JavaScript is a client-side scripting language.
13. What are JavaScript Data Types?
Following are the JavaScript Data types:
- Number
- String
- Boolean
- Object
- Undefined
14. What is negative Infinity?
Negative Infinity is a number in JavaScript which can be derived by dividing negative number by zero.
15. Is it possible to break JavaScript Code into several lines?
Breaking within a string statement can be done by using a backslash, ‘\,’ at the end of the first line.
Example:
document. Write ("This is \a program,");
And if you change to a new line when not within a string statement, then javaScript ignores the break in the line.
Example:
var x=1, y=2, z=x+y;
The above code is perfectly fine, though not advisable as it hampers debugging.
16. Explain JavaScript Event Delegation Model?
In JavaScript, there is some cool stuff that makes it the best of all. One of them is Delegation Model. When capturing and bubbling, allow functions to implement one single handler to many elements at one particular time then that is called event delegation. Event delegation allows you to add event listeners to one parent instead of specified nodes. That particular listener analyzes bubbled events to find a match on the child elements. Many people think it to be complicated but in reality, it is very simple if one starts understanding it.
17. Explain Arrow functions?
An arrow function is a consise and short way to write function expressions in Es6 or above.A rrow functions cannot be used as constructors and also does not supports this, arguments, super, or new.target keywords. It is best suited for non-method functions. In general an arrow function looks like const function_name= ()=>{}
const greet=()=>{console.log('hello');} greet();
18. List the comparison operators supported by Javascript?
Javascript supports below comparison operators
- > Greater than
- < Less than
- <= Less than or equal to
- >= Greater than or equal to
- == Equal to
- != Not Equal to
- === Equal to with datatype check
- !== Not equal to with datatype check
19. List HTML DOM mouse events?
HTML DOM mouse events
- onclick
- ondblclick
- mousemove
- mousedown
- mouseover
- mouseout
- mouseup
20. What is the purpose of the ‘bind’ method in JavaScript?
The ‘bind’ method is used to create a new function with a specific ‘this’ value and, optionally, pre-filled arguments. It allows you to bind a function to a particular object or context, ensuring that ‘this’ inside the function refers to the specified object when the function is invoked.
21. How can you check if an object has a specific property in JavaScript?
You can use the ‘hasOwnProperty()’ method to check if an object has a specific property. The method returns a boolean indicating whether the object has the specified property as a direct property and not inherited from its prototype chain.
22. What is the purpose of the ‘reduce’ method in JavaScript arrays?
The ‘reduce’ method is used to reduce an array to a single value by applying a function to each element and accumulating the result. It is often used to perform calculations like summing the values, finding the maximum/minimum, or transforming the array into a different data structure.
23. What is the purpose of the ‘localStorage’ object in JavaScript?
The ‘localStorage’ object provides a way to store key-value pairs locally in the browser. The data stored in ‘localStorage’ persists even after the browser is closed and can be accessed within the same domain.
24. What is the purpose of the ‘forEach’ method in JavaScript arrays?
The ‘forEach’ method is used to iterate over the elements of an array and execute a provided function once for each element. It is a concise way to perform an operation on each element without using a traditional for loop.
25. What is the purpose of the ‘push’ method in JavaScript arrays?
The ‘push’ method is used to add one or more elements to the end of an array. It modifies the original array by increasing its length and adding the provided elements as new elements.
26. How can you check if an object has a specific property in JavaScript?
You can use the ‘hasOwnProperty()’ method or the ‘in’ operator to check if an object has a specific property. The ‘hasOwnProperty()’ method returns a boolean indicating if the object has the property, while the ‘in’ operator also checks inherited properties.
27. What is Javascript BOM?
BOM stands for “Browser Object Modal” that allows Javascript to ‘talk’ to the browser, no standards, modern browsers implement similar BOMS – window, screen, location, history, navigator, timing, cookies.
28. How can you create an array in Javascript?
There are 3 different ways to create an array in Javascript. They are
- By array literal
usage: var myArray=[value1,value2…valueN]; - By creating instance of Array
usage:var myArray=new Array(); - By using an Array constructor
usage:var myArray=new Array(‘value1′,’value2′,…,’valueN’);
29. What is the difference between the substr() and substring() functions in JavaScript?
Difference between the substr() and substring() functions in JavaScript.
The substr() function has the form substr(startIndex,length). It returns the substring from startIndex and returns ‘length’ number of characters.
var s = "hello";
( s.substr(1,4) == "ello" ) // true
The substring() function has the form substring(startIndex,endIndex). It returns the substring from startIndex up to endIndex – 1.
var s = "hello";
( s.substring(1,4) == "ell" ) // true
30. How to add/remove properties to object dynamically in Javascript?
You can add a property to an object using object.property_name =value, delete object.property_name is used to delete a property.
Example:
let user = new Object();
// adding a property
user.name='Anil';
user.age =25;
console.log(user);
delete user.age;
console.log(user);
31. How to convert Javascript date to ISO standard?
toISOString() method is used to convert javascript date to ISO standard. It converts JavaScript Date object into a string, using the ISO standard.
Usage:
var date = new Date();
var n = date.toISOString();
console.log(n);
// YYYY-MM-DDTHH:mm:ss.sssZ
32. How to get inner Html of an element in JavaScript?
InnerHTML property of HTML DOM is used to get inner Html of an element in JavaScript.
Example Usage:
This is inner Element
<script type="text/javascript">
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // This is inner Element
document.getElementById("inner").innerHTML = "Html changed!";
var inner= document.getElementById("inner").innerHTML ;
console.log(inner); // Html changed!
</script>
33. List different ways of empty an array in Javascript?
In Javascript, there are many ways to empty an array in Javascript, below we have listed 4 major
- By assigning an empty array.
var arr1 =[1,4,5,6];
arr1=[];
- By assigning array length to 0.
var arr2 =[1,4,5,6];
arr2.length=0;
- By poping the elements of the array.
var arr2 =[1,4,5,6];
while(arr.length > 0) {
arr.pop();
}
- By using .splice() .
var arr =[1,4,5,6];
arr.splice(0,arr.length)
34. What is a prompt box?
A prompt is a type of box. It allows the user to enter their input, provide a text box, number, and text provided by label and box.
35. Explain the working of timers in JavaScript?
Timers are used to execute a bit of code at a set time and repeat the bit of code in a given interval.
Those working are done by using functions setTimeout, setInterval, clear interval.
Working of Functions:
The setTimeout(function, delay) function is used to start a timer, which calls a particular function after the, particularly mentioned delay.
The setInterval(function, delay) function is used to repeatedly execute the given function in the said delay and only stops when it is cancelled.
The clearInterval(id) function instructs or indicates the timer to stop (for stopping the given or mentioned function).
The whole timers are operated within a single thread, and for his events might wait or queue up, they wait for their execution.
36. What will be the output of the below code?
var myarray =new Array (1,4,3,6,10,0,22)
document.write(myarray.sort())
myarray.sort(function(a, b) { return b - a; });
document.write(myarray);
Ans: [0,1,10,22,3,4,6] and [22,10,6,4,3,1,0]
The sort() method sorts the elements of an array. The sort order can be either alphabetic or numeric, and either ascending (up) or descending (down). By default, the sort() method sorts the values as strings in alphabetical and ascending order.
37. What is the output of the below code?
function checkAge(age) {
if (age < 18) {
const message = “Sorry, you’re too young to get your driving license.”;
}
else {
const message = “Yay! You’re are eligible!”;
}
return message;
}
console.log(checkAge(21));
Ans: Reference Error
Variables with the const and let keyword are block-scoped. A block is anything between curly brackets ({ }). In this case, the curly brackets of the if/else statements. You cannot reference a variable outside of the block it’s declared in, a Reference Error gets thrown.
38. How many alert dialogs will the following Javascript generate, and what will be displayed in each of them?
var x = “20”;
function func1(){
var x = “5”;
alert(this.x);
function func2(){alert(x);}
func2();
}
func1();
Ans: A. There will be 2 alert dialogs. The first will display “20”, and the second will display “5”.
39. What are the different types of errors in JavaScript?
There are three types of errors:
- Load time errors: Errors that come up when loading a web page, like improper syntax errors, are known as Load time errors and generate the errors dynamically.
- Runtime errors: Errors that come due to misuse of the command inside the HTML language.
- Logical errors: These are the errors that occur due to the bad logic performed on a function with a different operation.
40. 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 is checked, this alert will return TRUE.
41. How should we change the style/class of an element?
First of all, we can use the className to assign a value directly to the class. If any such classes are already present on the element, then this will override them.
For getting the value of class on the element, we can add multiple spaces using className.
Given the following way, we can change the class of an element:
document.getElementById("myText").style.fontSize = "20";
or,
document.getElementById ("myText").className = "any class";
42. How to add a new property in existing function JavaScript?
It is easy to add a new property in existing function by just giving value to the existing function it. For example, let we have an existing object person, to give new property check the below code:
person.country= “India”;
The new property “country” has added to the object person.
43. Explain higher-order functions in JavaScript?
Higher order function is the best feature of functional programming available in JavaScript. It is the function which takes a function as an argument and returns a function as a result. Some of the inbuilt higher-order functions are mapping, filtering, reduction, zipping, etc.
44. Explain about Read and Write of a file using JavaScript?
Basically, there are two ways to read and write a file:
- Using JavaScript extensions.
- Using a web page and Active X objects.
Given are the steps to read and write a file:
Step 1:
file=fopen(getScriptPath(),0);
fread() is used for reading the file content
Step 2:
str = fread(file,flength(file);
The function fwrite() is used to write the contents of the file.
Step 3:
file = fopen("c:\MyFile.txt", 3);// it is used for opening the file for writing.
fwrite(file, str);
// str which is specified within the method is the content that is to be written into the file.
45. What is called Variable typing in JavaScript?
Variable typing is nothing much firstly, it is used to assign a number to a variable, and after that, the same variable is assigned t a String.
For Example:
i = 10;
i = "string";
So this is called variable typing. This concept of JS is similar to Java.
46. List the disadvantages of using innerHTML in javascript.
The innerHTML property is a part of the DOM and is used to set or return the HTML content of an element. The return value represents the text content of the HTML element. It allows JavaScript code to make changes to a website being rendered.
The disadvantages of using innerHTML are:
- Appending to innerHTML is not supported without reparsing the whole innerHTML.
- As reparsing is required for innerHTML the processing is slow and takes more time.
- The event handlers do not attach automatically to the newly created elements by setting innerHTML. One must keep track of the event handler and attach the new element manually.
- By using innerHTML if you add, append, delete or modify contents on a webpage all contents are replaced, also all the DOM nodes inside that element are reparsed and recreated.
- No proper validation is provided by innerHTML, hence any valid HTML code can be used. This may break the document of JavaScript.
47. Is JavaScript case-sensitive?
Yes, JavaScript is a case-sensitive language. JavaScript also has a set of rules for writing JavaScript programs or codes where the identifiers, variables, keywords, and function names must be written using an appropriate capitalization of letters.
For example:
<script>
var name,Name;
name=’abc’; //variable 1
Name=’def’; // variable 2
document.write(Name);
</script>
In JavaScript, name, and Name are not the same thing even if both variables are spelled the same.
48. 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”
49. How are DOM utilized in JavaScript?
DOM stands for Document Object Model and is responsible for how various objects in a document interact with each other. DOM is required for developing web pages, which includes objects like paragraphs, links, etc. These objects can be operated to include actions like add or delete. DOM is also required to add extra capabilities to a web page. On top of that, the use of API gives an advantage over other existing models.
50. What is the role of deferred scripts in JavaScript?
The HTML code’s parsing during page loading is paused by default until the script has not stopped executing. If the server is slow or the script is particularly heavy, then the web page is delayed.
While using Deferred, scripts delays execution of the script till the time the HTML parser is running. This reduces the loading time of web pages, and they get displayed faster.