img
JavaScript

JavaScript is a versatile language for building interactive web applications. It runs in the browser and enables real-time updates and user interactivity.

Last updated on:- 5th June 2023


1.
What are the different kind of data-types available in JavaScript ?

Here are the different data types in JavaScript classified based on whether they are primitive or non-primitive:
Primitive Data Types:
-Number
-String
-Boolean
-Null
-Undefined
-Symbol

Non-Primitive Data Types:
-Object
-Array
-Function
-Date
-RegExp

The primitive data types are atomic and immutable, meaning they are directly assigned and stored by value. On the other hand, non-primitive data types are mutable and are stored by reference.

2.
What is the difference between 'store by value' and 'store by reference' ?

Store by value:
Primitive data types such as numbers, strings, booleans, null, undefined, and symbols are stored by value. When a variable of a primitive type is assigned to another variable or passed as an argument to a function, a copy of the value is created and stored in the new variable. Any changes made to one variable do not affect the other variable because they hold independent copies of the value.

Example:
let a = 5;
let b = a;
b = 10;
console.log(a); // Output: 5
console.log(b); // Output: 10

Store by reference:
Objects, arrays, and functions are stored by reference.When an object is assigned to a variable or passed as an argument, the variable holds a reference or a pointer to the memory location where the object is stored. So, if we assign the same object to multiple variables or pass it to functions, all those variables or functions will refer to the same object in memory. Therefore, modifying the object through one variable will affect all the references to that object.

Example:
let arr1 = [1, 2, 3];
let arr2 = arr1;
arr2.push(4);
console.log(arr1); // Output: [1, 2, 3, 4]
console.log(arr2); // Output: [1, 2, 3, 4]

In summary, storing by value creates independent copies, while storing by reference creates references to the same data in memory, leading to shared changes.

3.
What are closures in JavaScript ?

A closure in JavaScript is a combination of a function and the lexical environment within which that function was declared. It allows a function to access variables from its outer scope even after the outer function has finished executing. In other words, a closure preserves the scope chain of the enclosing function at the time of its creation.

Example:

function outerFunction() {

const outerVariable = 'I am from the outer function';

function innerFunction() {
// Accessing outerVariable from the outer scope
console.log(outerVariable);
}

return innerFunction;
}

const closureExample = outerFunction();
closureExample(); // 'I am from the outer function'

4.
What is implicit type conversion in JavaScript ?

Implicit type conversion in JavaScript, also known as type coercion, refers to the automatic conversion of one data type to another by the JavaScript engine. It occurs when an operator or function expects operands of a certain type, but receives operands of a different type. JavaScript performs implicit type conversion to make the operation possible.

Example:
let num = 10;
let str = '5';
let result = num + str;
console.log(result); // '105'

In this example, we have a numeric variable num with a value of 10, and a string variable str with a value of '5'. When we use the + operator to concatenate num and str, JavaScript performs implicit type conversion. It converts the numeric value of num to a string and concatenates it with str. The result is the string '105', obtained by concatenating the converted num with str.

Implicit type conversion can occur in various situations, such as when performing arithmetic operations between different types, comparing values of different types, or using logical operators on non-boolean values. JavaScript automatically converts values to a common type to perform the operation.

5.
What is the difference between "null" and "undefined" in JavaScript ?

In JavaScript, both "null" and "undefined" represent the absence of a value, but they are used in different contexts.

The "null" value is an assignment value that indicates the intentional absence of any object value. It is a primitive value that can be assigned to a variable to explicitly indicate that it has no value or is empty. For example:

let myVariable = null;
console.log(myVariable); // Output: null

On the other hand, "undefined" is a built-in value in JavaScript that indicates the absence of a value or uninitialized variable. It is automatically assigned to variables that have been declared but not yet assigned a value or to function parameters that have not been provided with an argument. For example:

let myVariable;
console.log(myVariable); // undefined

function myFunction(parameter) {
console.log(parameter); // undefined
}

myFunction();

To summarize, "null" is an intentional absence of value, while "undefined" typically indicates an unintentional absence or lack of initialization.

6.
Explain briefly the core difference between "let", "const", and "var" in JavaScript.

In JavaScript, "let", "const", and "var" are used to declare variables, but they have some differences in terms of scope and reassignment.

1. "var": Variables declared with "var" have function scope or global scope. They can be redeclared and reassigned within their scope. "var" variables are hoisted to the top of their scope during the execution phase. For example:

function example() {
var x = 10;
if (true) {
var x = 20;
console.log(x); // 20
}
console.log(x); // 20
}

2. "let": Variables declared with "let" have block scope. They can be reassigned within their scope but cannot be redeclared in the same scope. "let" variables are not hoisted. For example:

function example() {
let x = 10;
if (true) {
let x = 20;
console.log(x); // 20
}
console.log(x); // 10
}

3. "const": Variables declared with "const" also have block scope like "let". However, they are used for values that are meant to remain constant and cannot be reassigned. "const" variables must be assigned a value at the time of declaration and cannot be redeclared or reassigned. For example:

function example() {
const x = 10;
if (true) {
const x = 20;
console.log(x); // 20
}
console.log(x); // 10
}

It is generally recommended to use "let" and "const" over "var" as they provide better scoping rules and help in preventing unintended bugs and issues related to variable reassignment.

7.
What is hoisting in JavaScript and how does it work ?

Hoisting is a JavaScript behavior where variable and function declarations are moved to the top of their respective scopes during the compilation phase. This allows variables and functions to be used before they are actually declared in the code.

Here's an example to illustrate hoisting:
```javascript
console.log(x); // Output: undefined
var x = 10;
console.log(x); // Output: 10
```

In the example above, even though the variable `x` is logged before its declaration, it doesn't result in an error. This is because the variable declaration `var x` gets hoisted to the top of its scope. However, only the declaration is hoisted, not the initialization. So, the first `console.log(x)` prints `undefined` because `x` is declared but not yet assigned a value. The second `console.log(x)` prints `10` after the variable `x` is assigned the value `10`.

8.
What is the difference between synchronous and asynchronous programming in JavaScript ?

Synchronous programming executes tasks in a sequential manner, where each task must complete before moving on to the next one.
Asynchronous programming, on the other hand, allows tasks to be executed independently and out of order, without blocking the execution of other tasks. Asynchronous programming is commonly used for tasks like fetching data from a server or handling user input.

9.
What is the purpose of the "this" keyword in JavaScript? Explain with an example.

The "this" keyword in JavaScript is used to refer to the object that the function is being executed within. It allows access to the properties and methods of the current object. The value of "this" is determined by how the function is called.

Here's an example to illustrate the use of the "this" keyword:

```javascript
var person = {
name: 'John',
greet: function() {
console.log('Hello, ' + this.name + '!');
}
};

person.greet(); // Output: Hello, John!
```

In the example above, the object `person` has a property `name` and a method `greet`. Inside the `greet` method, `this.name` accesses the `name` property of the current object (`person`). When `person.greet()` is called, it prints 'Hello, John!' because `this` refers to the `person` object.

10.
Explain the concept of event delegation in JavaScript.

Event delegation is a technique in which a single event listener is attached to a parent element, instead of attaching multiple event listeners to individual child elements. The parent element then handles events on behalf of its child elements.
This approach improves performance and allows dynamically added or removed child elements to automatically be included in the event handling.

11.
What is the purpose of the "use strict" directive in JavaScript ?

The "use strict" directive is used to enable strict mode in JavaScript. It enforces stricter rules for code execution, helps avoid common mistakes, and improves code quality. When "use strict" is added at the beginning of a script or a function, certain actions are no longer allowed, and certain behaviors are changed.

12.
Explain the concept of event bubbling and event capturing in JavaScript.

Event bubbling and event capturing are two different mechanisms to handle events in the DOM.
Event bubbling is the default behavior where an event is first triggered on the innermost element and then propagates up the DOM hierarchy through its ancestors.
Event capturing, on the other hand, allows capturing the event during the capturing phase, where the event is triggered on the outermost element first and then propagates down the DOM hierarchy towards the target element.
Both mechanisms provide flexibility in handling events and can be used based on the desired behavior.

13.
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 explicitly setting the value of "this" within a function, regardless of how the function is called. "bind()" returns a new function that, when executed, has its "this" value fixed to the provided value.

14.
How does JavaScript handle asynchronous operations ? Explain the concepts of callbacks, promises, and async/await.

JavaScript uses various techniques to handle asynchronous operations.
Callbacks are a traditional approach where a function is passed as an argument to another function to be executed once the asynchronous operation is complete.
Promises provide a more structured way to handle asynchronous code and allow chaining multiple operations.
Async/await is a syntax introduced in ECMAScript 2017 (ES8) that simplifies working with promises by using async functions and the "await" keyword to wait for the resolution of a promise.

15.
What is the event loop in JavaScript and how does it work ?

The event loop is a mechanism in JavaScript that handles the execution of asynchronous code. It ensures that tasks are executed in a non-blocking manner.
The event loop continuously checks for tasks in the event queue and executes them one by one. It allows JavaScript to handle operations like timers, I/O operations, and callbacks efficiently.

16.
What is the difference between "==" and "===" in JavaScript ?

The "==" operator compares the values of the operands after performing type coercion, while the "===" operator compares both the values and types of the operands without type coercion. Here is an example:

1. "==" (Equality Operator):
console.log(5 == '5'); // Output: true

2. "===" (Strict Equality Operator):
console.log(5 === '5'); // Output: false

Using the strict equality operator "===" is generally recommended in JavaScript because it avoids unexpected behavior caused by type coercion.

17.
What is the purpose of the "localStorage" and "sessionStorage" objects in JavaScript ?

"localStorage" and "sessionStorage" are web storage mechanisms provided by browsers to store data on the client-side. They are part of the Web Storage API. "localStorage" stores data with no expiration date, while "sessionStorage" stores data for a single session and is cleared when the session ends. They are useful for persisting data between page reloads or for sharing data within a specific session.

18.
How does JavaScript handle memory management ?

JavaScript uses automatic memory management through a technique called garbage collection. When an object is no longer referenced or accessible, the garbage collector identifies it as eligible for memory deallocation. The garbage collector then frees up the memory occupied by the object, making it available for future use.

19.
Explain the concept of prototypal inheritance in JavaScript.

Prototypal inheritance is a mechanism in JavaScript where objects can inherit properties and methods from other objects. Each object has an internal link to another object called its prototype. If a property or method is not found on an object, JavaScript looks up the prototype chain until it finds the property or method in one of the prototypes.

20.
How does JavaScript handle exceptions and what are the key components of error handling in JavaScript ?

JavaScript uses a try-catch-finally statement to handle exceptions. Code that might throw an exception is placed inside the "try" block, and if an exception occurs, it is caught in the "catch" block. The "finally" block is optional and is executed regardless of whether an exception occurred or not. Additionally, error objects in JavaScript have properties like name and message to provide information about the error.
img

"Embrace curiosity, unlock knowledge"

Copyright © 2023 - Some rights reserved

Made with

in INDIA