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

JavaScript Ques

The document provides a comprehensive overview of JavaScript, covering its definition, key features, and differences from Java. It explains various concepts such as variable scoping, closures, asynchronous programming, and the use of functions like promises and callbacks. Additionally, it addresses advanced topics like event handling, memory management, and the benefits of strict mode, along with practical examples.

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)
4 views

JavaScript Ques

The document provides a comprehensive overview of JavaScript, covering its definition, key features, and differences from Java. It explains various concepts such as variable scoping, closures, asynchronous programming, and the use of functions like promises and callbacks. Additionally, it addresses advanced topics like event handling, memory management, and the benefits of strict mode, along with practical examples.

Uploaded by

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

JavaScript

1. What is JavaScript, and how is it different from Java?


JavaScript is a dynamic, interpreted programming language primarily used for adding
interactivity to web pages. Java, on the other hand, is a statically typed, compiled language
used for building large-scale applications. JavaScript is interpreted at runtime, while Java is
compiled.

2. What are the key features of JavaScript?

● Dynamic typing
● Object-oriented programming (prototypal inheritance)
● First-class functions
● Event-driven programming
● Asynchronous programming (using promises, async/await)
● Lightweight and cross-platform.

3. Explain the difference between var, let, and const.

● var has function scope and can be redeclared or updated.


● let has block scope and cannot be redeclared but can be updated.
● const has block scope, cannot be redeclared or updated.

4. What is hoisting in JavaScript?


Hoisting is JavaScript's default behavior of moving declarations (variables and functions) to the
top of their containing scope during the compilation phase, allowing them to be used before
being declared.

5. What are closures in JavaScript, and how do they work?


A closure is a function that has access to its own scope, the outer function's scope, and the
global scope, even after the outer function has returned. Closures are created every time a
function is created, at function creation time.
6. What is the difference between == and ===?

● == checks for equality after type coercion.


● === checks for both equality and type without performing type coercion.

7. Explain the concept of prototypes in JavaScript.


Every JavaScript object has a prototype, which is another object from which it inherits properties
and methods. This allows for prototype-based inheritance, where objects can share behavior
through a chain of prototypes.

8. What is an Immediately Invoked Function Expression (IIFE)?


An IIFE is a function that is defined and executed immediately. It helps avoid polluting the global
scope by creating a local scope for variables.

js
Copy code
(function() {
console.log('IIFE');
})();

9. What is event delegation in JavaScript?


Event delegation is a technique where you attach a single event listener to a parent element to
manage events triggered by its child elements, rather than attaching individual event listeners to
each child.

10. What is the difference between synchronous and asynchronous code in JavaScript?

● Synchronous code is executed sequentially, one line at a time.


● Asynchronous code allows for non-blocking execution, enabling other operations to
continue while waiting for tasks (like network requests) to complete.

11. What is the purpose of the this keyword in JavaScript?


this refers to the object that is currently executing the code. In global contexts, this refers to
the global object (e.g., window in browsers), but its value depends on how a function is called.
12. What is the difference between null and undefined?

● null is an explicit assignment representing no value or an empty object.


● undefined means a variable has been declared but not yet assigned a value.

13. What are promises in JavaScript, and how do they work?


Promises represent the eventual completion (or failure) of an asynchronous operation and allow
you to handle the result or error using .then(), .catch(), and .finally() methods.

14. What is a callback function in JavaScript?


A callback function is a function passed into another function as an argument, which is invoked
inside the other function to complete a task.

15. Explain arrow functions in JavaScript and how they differ from regular functions.
Arrow functions are a concise syntax for writing functions. They do not have their own this
context and inherit this from the surrounding lexical context.

js
Copy code
const add = (a, b) => a + b;

16. What is the purpose of the bind(), call(), and apply() methods?
These methods are used to set the value of this in functions:

● bind() returns a new function with a specified this context.


● call() invokes the function immediately with a specified this and arguments.
● apply() is similar to call() but takes arguments as an array.

17. Explain how setTimeout and setInterval work in JavaScript.

● setTimeout runs a function after a specified delay.


● setInterval repeatedly runs a function at specified intervals.
18. What is an async/await function in JavaScript?
async/await is syntactic sugar over promises, making asynchronous code look synchronous.
An async function always returns a promise, and await pauses the execution until the promise
resolves or rejects.

19. What are template literals in JavaScript?


Template literals allow embedded expressions and multi-line strings using backticks (`) instead
of quotes. You can interpolate variables using ${}.

js
Copy code
const name = "John";
console.log(`Hello, ${name}!`);

20. What is the difference between map(), forEach(), filter(), and reduce()
methods in arrays?

● map() creates a new array with the results of applying a function to every element.
● forEach() executes a function for each array element, without returning a new array.
● filter() creates a new array with elements that pass a condition.
● reduce() reduces an array to a single value by applying a function cumulatively.

21. What is the spread operator, and how is it used?


The spread operator (...) expands an iterable (e.g., array, object) into individual elements.

js
Copy code
const arr = [1, 2, 3];
console.log(...arr); // 1 2 3

22. What are higher-order functions in JavaScript?


A higher-order function is a function that takes another function as an argument or returns a
function as a result.
23. What is the difference between deep copy and shallow copy?

● A shallow copy copies the top-level properties but nested objects share references.
● A deep copy creates a complete copy of an object, including nested objects.

24. Explain the concept of destructuring in JavaScript.


Destructuring allows you to unpack values from arrays or objects into distinct variables.

js
Copy code
const [a, b] = [1, 2];
const { name } = { name: "John", age: 30 };

25. What are JavaScript modules, and how do you export and import them?
JavaScript modules allow you to split your code into reusable files. You can use export to
make variables, functions, or classes available outside a module, and import to bring them into
another file.

js
Copy code
export const hello = () => console.log("Hello");
import { hello } from './module';

26. What is the DOM (Document Object Model) in JavaScript?


The DOM is a programming interface for HTML documents, representing the page's structure as
a tree of objects that can be manipulated with JavaScript.

27. How does JavaScript handle memory management and garbage collection?
JavaScript has an automatic garbage collector that identifies and frees memory occupied by
objects no longer in use, typically through reference counting and mark-and-sweep algorithms.
28. What are events in JavaScript, and how do you handle them?
Events are actions or occurrences detected by JavaScript (e.g., user clicks, form submission).
You can handle them using event listeners.

js
Copy code
document.addEventListener('click', () => console.log('Clicked!'));

29. What is the new keyword in JavaScript?


The new keyword is used to create an instance of an object or a constructor function.

js
Copy code
function Person(name) {
this.name = name;
}
const john = new Person("John");

30. Explain the concept of currying in JavaScript.


Currying is a technique where a function takes multiple arguments one at a time instead of all at
once.

js
Copy code
const add = a => b => a + b;
console.log(add(2)(3)); // 5

31. What is the event loop in JavaScript, and how does it work?
The event loop continuously checks the call stack and callback queue, executing functions from
the queue only when the stack is empty, enabling asynchronous behavior.

32. What are arrow functions, and how do they differ from traditional functions?
Arrow functions have a shorter syntax, and unlike traditional functions, they don't have their own
this context, which is lexically bound.
33. What are JavaScript objects, and how do you create them?
JavaScript objects are collections of key-value pairs. They can be created using object literals or
constructors.

js
Copy code
const person = { name: "John", age: 30 };

34. What is JSON, and how is it used in JavaScript?


JSON (JavaScript Object Notation) is a lightweight format for exchanging data. It can be parsed
with JSON.parse() and stringified with JSON.stringify().

35. What is strict mode in JavaScript, and how is it enabled?


Strict mode is a way to opt into a restricted variant of JavaScript, which catches common coding
errors and unsafe actions. It's enabled by adding "use strict"; at the top of a script or
function.

36. What is the difference between the find() and filter() methods in arrays?

● find() returns the first element that satisfies a condition.


● filter() returns an array of all elements that satisfy a condition.

37. What are getter and setter functions in JavaScript?


Getter and setter functions allow you to define methods for getting and setting the values of an
object’s properties.

js
Copy code
const person = {
firstName: "John",
get fullName() {
return this.firstName + " Doe";
},
set firstName(name) {
this.firstName = name;
}
};

38. What is NaN, and how can you check if a value is NaN?
NaN stands for "Not-a-Number". You can check if a value is NaN using the isNaN() function or
Number.isNaN().

39. What is the difference between let and var in terms of scope and hoisting?

● var is function-scoped, while let is block-scoped.


● var is hoisted and initialized with undefined, while let is hoisted but not initialized
(resulting in a "temporal dead zone" before initialization).

40. What is the difference between Array.slice() and Array.splice()?

● slice() returns a shallow copy of a portion of an array without modifying the original.
● splice() modifies the original array by removing, replacing, or adding elements.

41. What are try, catch, and finally blocks in JavaScript?


These blocks are used for handling exceptions:

● try contains code that may throw an error.


● catch handles the error if it occurs.
● finally executes code after try and catch, regardless of the outcome.

42. What is the typeof operator in JavaScript?


The typeof operator returns a string indicating the type of a variable or value.

43. Explain use strict in JavaScript and its benefits.


use strict enforces stricter parsing and error handling, helping to catch potential issues such
as undeclared variables or improper use of this.
44. What is function composition in JavaScript?
Function composition is the process of combining two or more functions to produce a new
function, where the result of one function is passed as the input to another.

45. How does JavaScript handle asynchronous operations?


JavaScript handles asynchronous operations through mechanisms like callbacks, promises, and
async/await. The event loop plays a critical role in ensuring non-blocking execution.

46. What is the eval() function in JavaScript, and why is it discouraged?


eval() executes a string of code as JavaScript. It’s discouraged because it poses security
risks and can lead to slow performance.

47. What are default parameters in JavaScript?


Default parameters allow function parameters to have default values if no argument is provided.

js
Copy code
function greet(name = 'Guest') {
console.log(`Hello, ${name}`);
}

48. What is event bubbling and event capturing in JavaScript?

● Event bubbling: The event starts at the target element and bubbles up to the ancestors.
● Event capturing: The event starts from the document and captures down to the target
element.

49. What is the difference between arrow functions and regular functions in terms of
this binding?
Arrow functions do not have their own this. They inherit this from the surrounding context.
Regular functions have their own this based on how they are called.
50. How do JavaScript promises prevent "callback hell"?
Promises flatten the nesting of callbacks by chaining .then() calls, making the code more
readable and easier to follow, compared to deeply nested callbacks.

You might also like