Javascript FAQ with examples

 Here is a comprehensive list of JavaScript FAQs with answers and examples. These cover key concepts, features, and common scenarios that developers often encounter.

1. What is JavaScript?

JavaScript is a high-level, interpreted programming language that is primarily used for creating interactive effects within web browsers. It enables developers to create dynamic content, such as interactive forms, animations, and games.

Example:

html
<!DOCTYPE html> <html> <head> <title>JavaScript Example</title> </head> <body> <h1>Hello, JavaScript!</h1> <script> alert("Welcome to JavaScript!"); </script> </body> </html>

2. What are variables in JavaScript?

Variables in JavaScript are used to store data that can be accessed and manipulated later. You declare variables using var, let, or const.

  • var is function-scoped (older way of declaring variables).
  • let is block-scoped and allows reassignment.
  • const is also block-scoped but does not allow reassignment.

Example:

javascript
let name = "John"; // String type variable const age = 30; // Constant variable name = "Jane"; // Reassignable (let) console.log(name); // Output: Jane console.log(age); // Output: 30

3. What is the difference between var, let, and const?

  • var: Function-scoped, can be re-assigned and redeclared.
  • let: Block-scoped, can be re-assigned but not redeclared.
  • const: Block-scoped, cannot be re-assigned or redeclared.

Example:

javascript
var x = 10; // function-scoped let y = 20; // block-scoped const z = 30; // block-scoped, immutable // x, y, and z can be modified (except const z, which cannot be reassigned) x = 15; y = 25;

4. What are functions in JavaScript?

Functions are reusable blocks of code that perform a specific task. They are defined using the function keyword or as an arrow function.

Example (Function Declaration):

javascript
function greet(name) { return "Hello, " + name; } console.log(greet("Alice")); // Output: Hello, Alice

Example (Arrow Function):

javascript
const greet = (name) => `Hello, ${name}`; console.log(greet("Bob")); // Output: Hello, Bob

5. What is a callback function?

A callback function is a function passed as an argument to another function, which is executed at a later time, usually after an event or operation is completed.

Example:

javascript
function fetchData(callback) { setTimeout(() => { console.log("Data fetched"); callback(); }, 2000); } fetchData(() => { console.log("Callback function executed"); });

6. What is a closure in JavaScript?

A closure is a function that "remembers" its lexical environment (i.e., the scope in which it was defined), even when the function is executed outside that scope.

Example:

javascript
function outerFunction() { let count = 0; return function innerFunction() { count++; console.log(count); }; } const counter = outerFunction(); counter(); // Output: 1 counter(); // Output: 2

7. What is event delegation?

Event delegation is a technique in JavaScript where a single event listener is added to a parent element instead of multiple listeners for child elements. This helps improve performance and ensures that dynamically added elements are also covered by the event listener.

Example:

html
<ul id="list"> <li>Item 1</li> <li>Item 2</li> <li>Item 3</li> </ul> <script> document.getElementById('list').addEventListener('click', function(event) { if (event.target.tagName === 'LI') { alert(event.target.textContent); } }); </script>

8. What are promises in JavaScript?

A Promise is an object representing the eventual completion or failure of an asynchronous operation. It allows you to handle asynchronous code more effectively using .then() for success and .catch() for errors.

Example:

javascript
const promise = new Promise((resolve, reject) => { let success = true; if (success) { resolve("Operation successful!"); } else { reject("Something went wrong!"); } }); promise .then(result => console.log(result)) // Output: Operation successful! .catch(error => console.log(error));

9. What is async/await?

async and await are syntactic sugar for working with promises. async is used to declare a function that returns a promise, and await is used inside the async function to wait for the promise to resolve.

Example:

javascript
function fetchData() { return new Promise(resolve => { setTimeout(() => { resolve("Data fetched successfully"); }, 2000); }); } async function getData() { const result = await fetchData(); console.log(result); // Output: Data fetched successfully } getData();

10. What is the difference between == and === in JavaScript?

  • == performs a type coercion (it converts the operands to the same type before comparing).
  • === performs a strict comparison (it does not convert types).

Example:

javascript
console.log(5 == '5'); // true (type coercion happens) console.log(5 === '5'); // false (no type coercion)

11. What are JavaScript data types?

JavaScript has several data types, including:

  • Primitive Types: string, number, boolean, undefined, null, symbol, bigint.
  • Reference Types: object, array, function.

Example:

javascript
let name = "Alice"; // string let age = 25; // number let isActive = true; // boolean let person = null; // null let obj = { name: "John", age: 30 }; // object let arr = [1, 2, 3]; // array

12. What is the difference between null and undefined?

  • null is an intentional assignment of "no value" and is explicitly set by the programmer.
  • undefined means a variable has been declared but has not been assigned a value.

Example:

javascript
let a; // undefined (variable declared, no value assigned) let b = null; // null (explicitly set to "no value") console.log(a); // Output: undefined console.log(b); // Output: null

13. What is the this keyword in JavaScript?

this refers to the context in which a function is executed. It can vary based on where and how a function is called.

Example:

javascript
function showThis() { console.log(this); } const obj = { name: "Alice", show: showThis }; obj.show(); // Output: { name: 'Alice', show: [Function: showThis] }

In the global context, this refers to the global object (window in browsers).

14. What is the difference between setTimeout() and setInterval()?

  • setTimeout() executes a function once after a specified delay.
  • setInterval() executes a function repeatedly with a specified interval.

Example:

javascript
// setTimeout example: setTimeout(() => { console.log("This runs after 2 seconds"); }, 2000); // setInterval example: setInterval(() => { console.log("This runs every 2 seconds"); }, 2000);

15. What are higher-order functions in JavaScript?

Higher-order functions are functions that take other functions as arguments or return functions. They enable more abstract and reusable code.

Example:

javascript
function multiply(a, b) { return a * b; } function higherOrderFunc(fn) { return fn(5, 10); } console.log(higherOrderFunc(multiply)); // Output: 50

16. What is destructuring in JavaScript?

Destructuring is a shorthand way of unpacking values from arrays or properties from objects into distinct variables.

Example (Array Destructuring):

javascript
const arr = [1, 2, 3]; const [a, b] = arr; console.log(a, b); // Output: 1 2

Example (Object Destructuring):

javascript
const person = { name: "John", age: 30 }; const { name, age } = person; console.log(name, age); // Output: John 30

Conclusion

These FAQs cover essential concepts of JavaScript that every developer should understand. From basic syntax, variables, and functions, to more advanced topics like promises, closures,

Comments

Popular posts from this blog

PrimeNG tutorial with examples using frequently used classes

Docker and Kubernetes Tutorials and QnA

Building strong foundational knowledge in frontend development topics