Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
0 views

JavaScript Interview Questions

This document contains a comprehensive list of JavaScript interview questions and answers covering various topics such as data types, functions, error handling, and DOM manipulation. Key concepts include differences between Java and JavaScript, the use of closures, and event bubbling. It also addresses practical coding examples and best practices for JavaScript programming.

Uploaded by

xenos8847
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views

JavaScript Interview Questions

This document contains a comprehensive list of JavaScript interview questions and answers covering various topics such as data types, functions, error handling, and DOM manipulation. Key concepts include differences between Java and JavaScript, the use of closures, and event bubbling. It also addresses practical coding examples and best practices for JavaScript programming.

Uploaded by

xenos8847
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 11

JavaScript Interview Questions

1. What are the differences between Java and JavaScript?

● Type: Java is a statically typed, compiled programming language, whereas JavaScript is


a dynamically typed, interpreted scripting language.
● Execution Environment: Java code runs on the Java Virtual Machine (JVM), while
JavaScript runs in web browsers or on servers (Node.js).
● Syntax and Structure: Java follows a class-based object-oriented structure, while
JavaScript is prototype-based.
● Use Cases: Java is commonly used for building enterprise-level applications, mobile
apps, and large systems, while JavaScript is primarily used for web development to
create interactive web pages.

2. What are Data Types in JavaScript?


JavaScript has several data types:

● Primitive Types:
○ Number: Represents both integer and floating-point numbers.
○ String: Represents text enclosed in quotes.
○ Boolean: Represents true or false values.
○ Undefined: Represents a variable that has been declared but not assigned a
value.
○ Null: Represents the intentional absence of any object value.
○ Symbol: A unique and immutable primitive value used as an identifier for object
properties.
● Reference Types:
○ Object: A collection of key-value pairs, including arrays and functions.

3. Which symbol is used for comments in JavaScript?


In JavaScript, comments can be written using:

● Single-line comments: // This is a comment


● Multi-line comments: /* This is a comment */

4. What would be the result of 3 + 2 + "7"?


The result would be "57". This happens because JavaScript performs the addition from left to
right. The first operation 3 + 2 results in 5, and then 5 + "7" results in string concatenation,
producing "57".

5. What is the use of the isNaN function?


The isNaN function is used to determine whether a value is NaN (Not-a-Number). It returns
true if the value is NaN and false otherwise. This function is useful for validating numeric
inputs and preventing erroneous calculations.

6. Which is faster in JavaScript and ASP script?


Generally, JavaScript is faster than ASP scripts for client-side operations because it runs in the
browser, directly interacting with the DOM without server round-trips. ASP (Active Server Pages)
is a server-side scripting language and may have higher latency due to server processing.

7. What is negative infinity?


Negative infinity is a special numeric value in JavaScript representing a value that is less than
any other number. It can be generated by dividing a negative number by zero (e.g., -1 / 0). It
is represented as -Infinity.

8. Is it possible to break JavaScript code into several lines?


Yes, you can break JavaScript code into several lines for better readability. You can do this in
several ways:

● Using line breaks inside statements.


● Using the continuation character \ (though it's rarely needed in JavaScript).
● Placing expressions inside parentheses to allow for multiline expressions.

9. Which company developed JavaScript?


JavaScript was developed by Netscape, and it was created by Brendan Eich in 1995.

10. What are undeclared and undefined variables?

● Undeclared variables: Variables that have not been declared at all, leading to a
ReferenceError if accessed. For example, console.log(x) where x was never
declared.
● Undefined variables: Variables that have been declared but not assigned a value. For
example, let x; console.log(x); will output undefined.

11. Write a JavaScript code for adding new elements dynamically.


You can add new elements dynamically to the DOM using JavaScript as follows:

javascript
Copy code
const newElement = document.createElement('div');
newElement.textContent = 'Hello, World!';
document.body.appendChild(newElement);

12. What are global variables? How are these variables declared, and what are the
problems associated with them?
Global variables are accessible from any part of the code, including inside functions. They can
be declared using the var, let, or const keywords outside of any function. Problems
associated with global variables include:

● Namespace pollution: Increases the risk of name collisions.


● Difficult debugging: Makes tracking changes and flow more complex.
● Memory usage: Remains in memory for the duration of the program.

13. What do you mean by NULL in JavaScript?


null is a primitive value in JavaScript that represents the intentional absence of any object
value. It is an assignment value, meaning you can set a variable to null to indicate that it
currently has no value or object.

14. How to delete property-specific values?


You can delete specific properties from an object using the delete operator. Example:

javascript
Copy code
const obj = { name: 'Alice', age: 25 };
delete obj.age; // The age property is removed from the object

15. What is a prompt box?


A prompt box is a dialog box that prompts the user for input. It can be created using the
prompt() method, which displays a message and an input field for the user to enter a value.
Example:

javascript
Copy code
const name = prompt("Please enter your name:");

16. What is the ‘this’ keyword in JavaScript?


The this keyword refers to the current context or scope of the execution. Its value depends on
how a function is called:

● In a method, this refers to the object it belongs to.


● In a regular function, this refers to the global object (or undefined in strict mode).
● In an arrow function, this retains the value of the enclosing lexical context.

17. Explain the working of timers in JavaScript. Also explain the drawbacks of using the
timer, if any.
Timers in JavaScript can be created using setTimeout() and setInterval().

● setTimeout() schedules a single execution of a function after a specified delay.


● setInterval() repeatedly executes a function at specified intervals.

Drawbacks:

● Inaccuracy: Timers may not execute exactly on time due to the single-threaded nature
of JavaScript.
● Resource consumption: Using many intervals can lead to performance issues.

18. What is the difference between ViewState and SessionState?

● ViewState: Used to preserve page and control values between postbacks. It is stored in
a hidden field on the page and sent back and forth between the server and the client.
● SessionState: Maintains user-specific data across multiple pages. It is stored on the
server and can be accessed from any page during a user's session.

19. How to submit a form using JavaScript?


You can submit a form using JavaScript by calling the submit() method on the form element.
Example:

javascript
Copy code
document.getElementById('myForm').submit();

20. Does JavaScript support automatic type conversion?


Yes, JavaScript supports automatic type conversion, also known as type coercion. This occurs
when values of different types are combined, and JavaScript automatically converts one type to
another. For example:

javascript
Copy code
const result = '5' + 3; // result is '53' (string)

21. What are all the looping structures in JavaScript?


JavaScript supports several looping structures:

● for loop: Used for iterating a specific number of times.


● while loop: Repeats as long as a condition is true.
● do...while loop: Similar to the while loop but executes at least once.
● for...of loop: Iterates over iterable objects (like arrays).
● for...in loop: Iterates over the keys of an object.

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


You can change the style or class of an element using JavaScript as follows:
javascript
Copy code
const element = document.getElementById('myElement');
element.style.color = 'red'; // Change style
element.className = 'newClass'; // Change class

23. Explain how to read and write a file using JavaScript?


In a browser environment, you cannot directly read or write files to the local filesystem due to
security restrictions. However, you can use the File API to read files selected by the user:

javascript
Copy code
const input = document.getElementById('fileInput');
input.addEventListener('change', function(event) {
const file = event.target.files[0];
const reader = new FileReader();
reader.onload = function(e) {
console.log(e.target.result); // Read file content
};
reader.readAsText(file);
});

For writing files, you can create a downloadable link with a Blob:

javascript
Copy code
const blob = new Blob(['Hello, World!'], { type: 'text/plain' });
const link = document.createElement('a');
link.href = URL.createObjectURL(blob);
link.download = 'hello.txt';
document.body.appendChild(link);
link.click();

24. What is called Variable typing in JavaScript?


Variable typing refers to the ability of JavaScript to automatically determine the type of a variable

4o mini

You said:
Answer rest of the question
ChatGPT said:
ChatGPT

Here are the answers to the remaining JavaScript questions:

25. How to convert the string of any base to integer in JavaScript?


You can use the parseInt() function to convert a string from any base to an integer. The
second argument specifies the base. For example:

javascript
Copy code
const binaryString = "1010";
const decimalNumber = parseInt(binaryString, 2); // Converts binary to
decimal
console.log(decimalNumber); // Output: 10

26. Explain how to detect the operating system on the client machine?
You can detect the operating system using the navigator.userAgent property. Here’s an
example:

javascript
Copy code
const userAgent = navigator.userAgent;
let os = "Unknown OS";

if (userAgent.indexOf("Win") !== -1) os = "Windows";


if (userAgent.indexOf("Mac") !== -1) os = "MacOS";
if (userAgent.indexOf("X11") !== -1 || userAgent.indexOf("Linux") !==
-1) os = "Unix/Linux";
if (userAgent.indexOf("Android") !== -1) os = "Android";
if (userAgent.indexOf("like Mac") !== -1) os = "iOS";

console.log(os);

27. What are the types of Pop-up boxes available in JavaScript?


There are three types of pop-up boxes in JavaScript:

Alert box: Displays a message and an OK button.


javascript
Copy code
alert("This is an alert box!");

Confirmation box: Displays a message and OK and Cancel buttons, returning true or false
based on user action.
javascript
Copy code
const confirmed = confirm("Are you sure?");

Prompt box: Displays a message with an input field for user input.
javascript
Copy code
const userInput = prompt("Please enter your name:");

28. What is the difference between an alert box and a confirmation box?

● Alert Box: Used to display a message to the user. It does not return any value.
● Confirmation Box: Used to confirm an action. It returns true if the user clicks OK and
false if the user clicks Cancel.

29. What is the disadvantage of using innerHTML in JavaScript?


Using innerHTML can lead to security vulnerabilities such as Cross-Site Scripting (XSS) if user
input is not properly sanitized. It can also cause performance issues, as it forces the browser to
reparse and reflow the entire DOM structure.

30. What is the use of void(0)?


void(0) is often used in hyperlinks to prevent the default action of the link from being
executed. It returns undefined and is sometimes used to call JavaScript functions without
navigating away from the page.

html
Copy code
<a href="javascript:void(0);" onclick="myFunction()">Click me</a>

31. What is the ‘Strict’ mode in JavaScript and how can it be enabled?
Strict mode is a feature in JavaScript that helps catch common coding errors and "unsafe"
actions, such as assigning values to undeclared variables. It can be enabled by adding "use
strict"; at the beginning of a script or a function.

javascript
Copy code
"use strict";
let x = 3.14; // This is fine
undeclaredVar = 5; // This will throw an error in strict mode

32. How to get the status of a CheckBox?


You can get the status of a checkbox using the checked property of the checkbox element:

javascript
Copy code
const checkbox = document.getElementById('myCheckbox');
const isChecked = checkbox.checked; // true if checked, false
otherwise

33. How to explain closures in JavaScript and when to use it?


A closure is a function that retains access to its lexical scope, even when the function is
executed outside that scope. Closures are useful for:

● Encapsulating variables and functions.


● Creating private variables or methods.
● Maintaining state in asynchronous operations. Example:

javascript
Copy code
function createCounter() {
let count = 0; // Private variable
return function() {
count++;
return count; // Closure
};
}
const counter = createCounter();
console.log(counter()); // 1
console.log(counter()); // 2

34. What is the difference between call() and apply() methods?


Both call() and apply() are used to invoke functions with a specific this value. The
difference is in how arguments are passed:

● call(): Takes arguments individually.


javascript
Copy code
function greet(greeting) {
console.log(`${greeting}, ${this.name}`);
}
const obj = { name: 'Alice' };
greet.call(obj, 'Hello'); // Output: Hello, Alice

● apply(): Takes an array of arguments.

javascript
Copy code
greet.apply(obj, ['Hi']); // Output: Hi, Alice

35. How to target a particular frame from a hyperlink in JavaScript?


You can target a specific frame in a webpage using the target attribute in anchor tags or
JavaScript. For example, in an anchor tag:

html
Copy code
<a href="page.html" target="myFrame">Open in Frame</a>

In JavaScript, you can use:

javascript
Copy code
window.frames['myFrame'].location.href = 'page.html';

36. Write the errors shown in JavaScript?


Common types of errors in JavaScript include:

● SyntaxError: Incorrect syntax.


● ReferenceError: Attempting to reference a variable that is not declared.
● TypeError: Operation on a value of an inappropriate type (e.g., calling a non-function).
● RangeError: Numeric value outside of allowable range.
● EvalError: Incorrect use of eval() function.

37. What is the difference between JavaScript and JScript?


JavaScript is a scripting language developed by Netscape, whereas JScript is Microsoft's
implementation of JavaScript. Both share similar syntax but may have different features and
functionalities due to their development environments.

38. What does var myArray = [[]]; statement declare?


This statement declares a variable myArray and initializes it as a two-dimensional array (an
array containing another array). It can hold multiple arrays or data sets.

javascript
Copy code
const myArray = [[]]; // An empty array within another array

39. How many ways can an HTML element be accessed in JavaScript code?
HTML elements can be accessed in several ways:

● getElementById: document.getElementById('elementId')
● getElementsByClassName:
document.getElementsByClassName('className')
● getElementsByTagName: document.getElementsByTagName('tagName')
● querySelector: document.querySelector('.className') or
document.querySelector('#elementId')
● querySelectorAll: document.querySelectorAll('selector')

40. What is the difference between innerHTML & innerText?

● innerHTML: Returns or sets the HTML content (including tags) of an element. It can
manipulate HTML structure.

javascript
Copy code
element.innerHTML = '<span>New Content</span>'; // Sets HTML content

● innerText: Returns or sets the plain text content of an element, ignoring any HTML tags.

javascript
Copy code
element.innerText = 'New Content'; // Sets plain text content

41. What is event bubbling in JavaScript?


Event bubbling is a process in the event propagation model where an event starts from the
target element and bubbles up to its ancestors (parent elements). You can handle events at
different levels of the DOM, allowing parent elements to respond to events triggered by child
elements.

You might also like