Javascript
Javascript
1. What is JavaScript?
Answer: JavaScript is a high-level, interpreted programming language
that is primarily used to create interactive and dynamic content on
web pages. It is an essential part of web development, alongside
HTML and CSS.
2. What are the different data types in JavaScript?
Answer: JavaScript supports several data types, including:
Primitive types: string, number, boolean, null, undefined, symbol, and
bigint
Objects: Object, Array, Function, Date, RegExp, and more.
3. What is the difference between let, const, and var?
Answer:
var: Function-scoped or globally-scoped if declared outside a
function, can be re-declared and updated.
let: Block-scoped, can be updated but not re-declared within the same
scope.
const: Block-scoped, cannot be updated or re-declared. However, the
properties of objects declared with const can be modified.
4. What is a closure in JavaScript?
Answer: A closure is a function that retains access to its lexical scope,
even when the function is executed outside that scope. This allows a
function to "remember" the environment in which it was created.
5. Explain event delegation in JavaScript.
Answer: Event delegation is a technique where a single event listener
is added to a parent element to manage events for its child elements.
This is efficient as it reduces the number of event listeners and utilizes
event bubbling.
6. What is the difference between == and === in JavaScript?
Answer: == (loose equality) checks for equality after performing type
conversion if necessary, while === (strict equality) checks for
equality without type conversion, meaning both value and type must
be the same.
7. What is the purpose of the this keyword in JavaScript?
Answer: The this keyword refers to the object it belongs to. Its value
depends on the context in which it is used, such as within a method, a
function, or in global scope.
8. What are promises in JavaScript?
Answer: Promises are objects that represent the eventual completion
(or failure) of an asynchronous operation and its resulting value. A
promise can be in one of three states: pending, fulfilled, or rejected.
9. What is an arrow function and how is it different from a
regular function?
Answer: Arrow functions provide a shorter syntax for writing
functions and do not have their own this binding. Instead, this is
lexically inherited from the surrounding scope.
// Regular function
function add(a, b) {
return a + b;
}
// Arrow function
const add = (a, b) => a + b;
10. What are the different ways to create an object in
JavaScript?
Answer: Objects can be created in several ways:
Using object literals:
const obj = { key: 'value' };
Using the new keyword with a constructor function:
function Person(name) {
this.name = name;
}
const person1 = new Person('John');
Using Object.create() method:
const proto = { key: 'value' };
const obj = Object.create(proto);
11. What is asynchronous programming and how does
JavaScript handle it?
Answer: Asynchronous programming allows the program to perform
tasks without blocking the main thread. JavaScript handles
asynchronous operations using callbacks, promises, and async/await
syntax.
12. What is the event loop in JavaScript?
Answer: The event loop is a mechanism that allows JavaScript to
perform non-blocking I/O operations, despite being single-threaded. It
continuously checks the call stack and the task queue to execute code,
collect events, and execute queued tasks.
13. What is the difference between call, apply, and bind?
Answer:
call: Invokes a function with a specified this value and arguments
provided individually.
apply: Invokes a function with a specified this value and arguments
provided as an array.
bind: Creates a new function that, when called, has its this value set to
a specified value, with a given sequence of arguments preceding any
provided when the new function is called.
function greet(greeting, punctuation) {
console.log(greeting + ', ' + this.name + punctuation);
}
const person = { name: 'Alice' };
Example:
const { a, b, ...rest } = { a: 1, b: 2, c: 3, d: 4 };
console.log(a); // 1
console.log(b); // 2
console.log(rest); // { c: 3, d: 4 }
4. Function Arguments
When dealing with function arguments, especially in functions where
you don't know how many arguments will
be passed, the rest operator can help you manage them efficiently.
Example:
function logArguments(...args) {
args.forEach(arg => console.log(arg));
}
logArguments('one', 'two', 'three');
// one
// two
// three
Summary
The rest operator is versatile and simplifies handling variable numbers
of parameters and properties in functions,
arrays, and objects. Its main uses are:
Function Parameters: Capturing all arguments passed to a function.
Array Destructuring: Collecting remaining elements in an array.
Object Destructuring: Collecting remaining properties in an object.
Managing Function Arguments: Simplifying the handling of a
variable number of arguments.
Using the rest operator makes code more concise and readable,
especially when dealing with collections of data
or dynamic parameters.
20. What is shallow copy and deep copy?
In JavaScript, the concepts of shallow copy and deep copy refer to the
ways in which objects or arrays are
duplicated. The key difference lies in how these copies handle nested
objects or arrays.
Shallow Copy
A shallow copy of an object or array is a new object or array that has
copies of the references to the original
object or array's elements. If the original object contains other
objects or arrays as its properties, the shallow
copy will have references to those same objects or arrays, not
duplicates.
Deep Copy
A deep copy of an object or array is a new object or array that is an
entirely independent copy of the original.
This means that all levels of nested objects or arrays are also copied,
resulting in a completely separate object or
array that shares no references with the original.
Methods for Creating Copies
Shallow Copy Methods:
Object.assign():
let shallowCopy = Object.assign({}, originalObject);
Spread Operator (...):
function deepCopy(obj) {
if (obj === null || typeof obj !== 'object') return obj;
if (Array.isArray(obj)) {
return obj.map(item => deepCopy(item));
}
const copy = {};
for (let key in obj) {
if (obj.hasOwnProperty(key)) {
copy[key] = deepCopy(obj[key]);
}
}
return copy;
}
JSON.parse(JSON.stringify()):
This method is simpler and works well for plain objects and arrays
but has limitations. It cannot handle functions,
undefined, Infinity, NaN, and other non-serializable data.