1.
Different Data Types in JavaScript:
o string: Represents text data. Example: "Hello, world!"
o number: Represents numeric values, both integers and floats.
Example: 42, 3.14
o boolean: Represents a value that can be either true or false.
o object: Represents a collection of properties. Example: { name:
'Alice', age: 30 }
o undefined: Represents a variable that has been declared but
not yet assigned a value.
o null: Represents a deliberate non-value or empty value.
o symbol (ES6): Represents a unique and immutable value used
as the key for object properties.
o bigint (ES11): Represents integers with arbitrary precision.
Example: 1234567890123456789012345678901234567890n
2. Difference between var, let, and const:
o var: Function-scoped or globally-scoped; can be re-assigned and
re-declared; hoisted.
o let: Block-scoped; can be re-assigned but not re-declared in the
same block; not hoisted to the block's top.
o const: Block-scoped; cannot be re-assigned or re-declared; the
variable must be initialized when declared.
3. Closure in JavaScript:
o A closure is a feature where a function retains access to its
lexical scope, even when the function is executed outside that
scope.
o Example:
javascript
Copy code
function outerFunction() {
let outerVariable = 'I am from outer!';
function innerFunction() {
console.log(outerVariable); // Accessing outerVariable
return innerFunction;
let closureFunction = outerFunction();
closureFunction(); // Logs: 'I am from outer!'
4. this Keyword in JavaScript:
o Refers to the object that is executing the current function.
o In global scope, this refers to the global object (window in
browsers).
o In an object method, this refers to the object itself.
o In a constructor function, this refers to the newly created
instance.
o In arrow functions, this is lexically bound to the surrounding
context.
5. Event Delegation:
o Event delegation is a technique where you attach a single event
listener to a parent element instead of multiple listeners on
individual child elements. This leverages event bubbling to
handle events efficiently.
o Example:
javascript
Copy code
document.getElementById('parent').addEventListener('click', function(event)
{
if (event.target && event.target.matches('button')) {
console.log('Button clicked!');
}
});
6. Prototypal Inheritance:
o In JavaScript, objects inherit properties and methods from other
objects via the prototype chain. An object can have a prototype
object which it inherits properties and methods from.
o Example:
javascript
Copy code
function Person(name) {
this.name = name;
Person.prototype.sayHello = function() {
console.log('Hello, ' + this.name);
};
let alice = new Person('Alice');
alice.sayHello(); // Logs: 'Hello, Alice'
7. JavaScript Promises:
o Promises represent the eventual completion (or failure) of an
asynchronous operation and its resulting value. They have three
states: pending, fulfilled, and rejected.
o Example:
javascript
Copy code
let myPromise = new Promise((resolve, reject) => {
setTimeout(() => resolve('Data received'), 1000);
});
myPromise.then(data => console.log(data)); // Logs: 'Data received'
8. Difference between == and ===:
o ==: Equality operator that performs type coercion before
comparing.
o ===: Strict equality operator that does not perform type
coercion; compares both value and type.
9. Callbacks:
o Callbacks are functions passed as arguments to other functions
and are executed after the completion of some task.
o Example:
javascript
Copy code
function doSomething(callback) {
// Perform some task
callback();
doSomething(() => console.log('Task completed'));
o Difference from Promises: Callbacks can lead to "callback
hell" (nested callbacks). Promises provide a cleaner way to
handle asynchronous operations and chaining.
10. Difference between null and undefined:
o null: Explicitly assigned to indicate an empty or non-existent
value.
o undefined: Represents a variable that has been declared but
not yet assigned a value.
11. Purpose of bind() Method:
o bind() creates a new function that, when called, has its this
keyword set to the provided value and is pre-set with given
arguments.
o Example:
javascript
Copy code
function greet() {
console.log('Hello, ' + this.name);
let person = { name: 'Alice' };
let greetAlice = greet.bind(person);
greetAlice(); // Logs: 'Hello, Alice'
12. Difference between map() and forEach():
o map(): Creates a new array with the results of calling a provided
function on every element in the calling array.
o forEach(): Executes a provided function once for each array
element but does not return a new array.
o Example:
javascript
Copy code
let numbers = [1, 2, 3];
let squares = numbers.map(x => x * x); // [1, 4, 9]
numbers.forEach(x => console.log(x)); // Logs each number
13. Fetch API:
o The Fetch API is used to make network requests to servers. It
returns a Promise that resolves to the Response object
representing the response to the request.
o Example:
javascript
Copy code
fetch('https://api.example.com/data')
.then(response => response.json())
.then(data => console.log(data))
.catch(error => console.error('Error:', error));
14. Event Bubbling and Event Capturing:
o Event Bubbling: The event starts from the target element and
bubbles up to the root.
o Event Capturing: The event starts from the root and
propagates down to the target element.
o Example:
javascript
Copy code
document.getElementById('parent').addEventListener('click', () =>
console.log('Parent Clicked'), true); // Capturing phase
document.getElementById('child').addEventListener('click', () =>
console.log('Child Clicked')); // Bubbling phase
15. Purpose of typeof Operator:
o Used to get the type of a variable or expression.
o Example:
javascript
Copy code
console.log(typeof 'Hello'); // 'string'
console.log(typeof 123); // 'number'
16. Template Literals:
o Template literals are string literals allowing embedded
expressions and multi-line strings. They are enclosed by
backticks (`).
o Example:
javascript
Copy code
let name = 'Alice';
let message = `Hello, ${name}!`;
console.log(message); // 'Hello, Alice!'
17. Difference between call(), apply(), and bind():
o call(): Calls a function with a given this value and arguments
provided individually.
o apply(): Calls a function with a given this value and arguments
provided as an array.
o bind(): Returns a new function with a given this value and initial
arguments. It does not execute the function immediately.
o Example:
javascript
Copy code
function greet(greeting) {
console.log(greeting + ', ' + this.name);
let person = { name: 'Alice' };
greet.call(person, 'Hello'); // 'Hello, Alice'
greet.apply(person, ['Hi']); // 'Hi, Alice'
let greetAlice = greet.bind(person, 'Hey');
greetAlice(); // 'Hey, Alice'
18. JavaScript Event Loop:
o The event loop manages the execution of code, handling of
events, and execution of queued tasks. It allows JavaScript to
perform non-blocking operations by offloading tasks to the
background and processing them in the main thread's loop.
19. Handling Errors:
o Use try...catch blocks to handle exceptions in synchronous code.
o For asynchronous code, handle errors using .catch() in promises
or try...catch with async/await.
o Example:
javascript
Copy code
try {
// Some code that may throw an error
} catch (error) {
console.error(error);
20. IIFEs (Immediately Invoked Function Expressions):
o An IIFE is a function expression that executes immediately after
its creation. It helps create a new scope.
o Example:
javascript
Copy code
(function() {
console.log('This function runs immediately');
})();
21. Hoisting in JavaScript:
o Hoisting is JavaScript's behavior of moving variable and function
declarations to the top of their scope before code execution.
o Example:
javascript
Copy code
console.log(x); // undefined
var x = 5;
22. Creating an Object in JavaScript:
o Object Literal:
javascript
Copy code
let obj = { name: 'Alice', age: 30 };
o Constructor Function:
javascript
Copy code
function Person(name, age) {
this.name = name;
this.age = age;
let person = new Person('Alice', 30);
o Class Syntax (ES6):
javascript
Copy code
class Person {
constructor(name, age) {
this.name = name;
this.age = age;
let person = new Person('Alice', 30);
23. Difference between Object.keys(), Object.values(), and
Object.entries():
o Object.keys(obj): Returns an array of the object's own
enumerable property names.
o Object.values(obj): Returns an array of the object's own
enumerable property values.
o Object.entries(obj): Returns an array of the object's own
enumerable property [key, value] pairs.
o Example:
javascript
Copy code
let obj = { a: 1, b: 2 };
console.log(Object.keys(obj)); // ['a', 'b']
console.log(Object.values(obj)); // [1, 2]
console.log(Object.entries(obj)); // [['a', 1], ['b', 2]]
24. JavaScript Generator Function:
o A generator function is a special type of function that can be
paused and resumed, allowing for the production of a sequence
of values.
o Example:
javascript
Copy code
function* counter() {
yield 1;
yield 2;
yield 3;
let gen = counter();
console.log(gen.next().value); // 1
console.log(gen.next().value); // 2
console.log(gen.next().value); // 3
25. Manipulating the DOM in JavaScript:
o Use methods like document.getElementById(),
document.querySelector(), and document.createElement() to
select, create, and modify DOM elements.
o Example:
javascript
Copy code
let elem = document.createElement('div');
elem.textContent = 'Hello, World!';
document.body.appendChild(elem);
jQuery Questions
1. What is jQuery, and Why is it Used?
o jQuery is a fast, small, and feature-rich JavaScript library. It
simplifies things like HTML document traversal and manipulation,
event handling, and animation. It's used to streamline cross-
browser JavaScript development.
2. Selecting Elements using jQuery:
o Use the $ function with a selector to select elements.
o Example:
javascript
Copy code
let element = $('#myElement'); // Selects element with id 'myElement'
3. Purpose of $(document).ready():
o Ensures that the DOM is fully loaded and ready to be
manipulated before executing code.
o Example:
javascript
Copy code
$(document).ready(function() {
console.log('DOM is ready!');
});
4. Handling Events in jQuery:
o Use methods like .click(), .on(), .off() to handle events.
o Example:
javascript
Copy code
$('#myButton').click(function() {
alert('Button clicked!');
});
5. jQuery Selectors:
o jQuery selectors are used to find and manipulate DOM elements.
o Example:
javascript
Copy code
$('.className'); // Selects elements with class 'className'
$('#idName'); // Selects element with id 'idName'
6. Manipulating DOM Elements using jQuery:
o Use methods like .html(), .text(), .append(), .prepend() to
manipulate content.
o Example:
javascript
Copy code
$('#myElement').html('New content');
7. Purpose of `.each() Method:
o Iterates over a jQuery collection, executing a function for each
matched element.
o Example:
javascript
Copy code
$('li').each(function(index) {
console.log('Item ' + index + ': ' + $(this).text());
});
8. fadeIn() and fadeOut() Methods:
o .fadeIn(): Fades in an element by gradually changing its opacity.
o .fadeOut(): Fades out an element by gradually changing its
opacity.
o Example:
javascript
Copy code
$('#myElement').fadeIn();
$('#myElement').fadeOut();
9. Performing AJAX Requests using jQuery:
o Use $.ajax(), $.get(), $.post() to perform AJAX requests.
o Example:
javascript
Copy code
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
success: function(data) {
console.log(data);
},
error: function(error) {
console.error('Error:', error);
});
10. Difference between .hide() and .fadeOut():
o .hide(): Hides an element immediately without animation.
o .fadeOut(): Hides an element by gradually changing its opacity.
11. Animating Properties of DOM Elements:
o Use the .animate() method to create custom animations.
o Example:
javascript
Copy code
$('#myElement').animate({ opacity: 0.5, left: '250px' }, 1000);
12. jQuery Plugins:
o jQuery plugins are extensions that add functionality to jQuery.
You include them in your project and use them like any other
jQuery method.
o Example:
javascript
Copy code
$(document).ready(function() {
$('#myElement').pluginName();
});
13. Difference between .attr() and .prop():
o .attr(): Gets or sets attributes of DOM elements (like href, id).
o .prop(): Gets or sets properties of DOM elements (like checked,
disabled).
14. Handling Form Submissions using jQuery:
o Use .submit() method or .on('submit') event to handle form
submissions.
o Example:
javascript
Copy code
$('form').on('submit', function(event) {
event.preventDefault(); // Prevents default form submission
console.log('Form submitted');
});
15. Event Delegation in jQuery:
o Attach an event handler to a parent element to handle events for
dynamically added child elements.
o Example:
javascript
Copy code
$('#parent').on('click', 'button', function() {
console.log('Button clicked');
});
16. Chaining Multiple jQuery Methods:
o jQuery methods return the jQuery object, allowing for method
chaining.
o Example:
javascript
Copy code
$('#myElement').css('color', 'red').slideUp().slideDown();
17. Difference between .html() and .text():
o .html(): Gets or sets the HTML content of elements.
o .text(): Gets or sets the text content of elements, escaping
HTML.
18. Adding or Removing CSS Classes using jQuery:
o Use .addClass(), .removeClass(), and .toggleClass() to manage
CSS classes.
o Example:
javascript
Copy code
$('#myElement').addClass('active');
$('#myElement').removeClass('inactive');
19. Using .data() Method:
o Stores or retrieves data associated with the matched elements.
o Example:
javascript
Copy code
$('#myElement').data('key', 'value');
console.log($('#myElement').data('key')); // 'value'
20. Getting or Setting Form Element Values using jQuery:
o Use .val() to get or set the value of form elements.
o Example:
javascript
Copy code
$('#myInput').val('New value');
21. Purpose of .on() and .off() Methods:
o .on(): Attaches event handlers to elements.
o .off(): Removes event handlers from elements.
22. Making an Element Draggable in jQuery UI:
o Use the .draggable() method from jQuery UI.
o Example:
javascript
Copy code
$('#myElement').draggable();
23. .queue() Method in jQuery:
o Manages a queue of functions to be executed on the selected
elements.
o Example:
javascript
Copy code
$('#myElement').queue(function(next) {
console.log('First in the queue');
next();
}).queue(function(next) {
console.log('Second in the queue');
});
24. .trigger() Method:
o Triggers a specified event on the selected elements.
o Example:
javascript
Copy code
$('#myElement').trigger('click');
25. Handling Errors in jQuery AJAX Calls:
o Use the error callback in $.ajax() to handle errors.
o Example:
javascript
Copy code
$.ajax({
url: 'https://api.example.com/data',
method: 'GET',
error: function(xhr, status, error) {
console.error('AJAX Error:', error);
}
});