What is JavaScript?

JavaScript is a high-level, interpreted programming language primarily used for creating dynamic and interactive web content. It runs in the browser environment and allows developers to manipulate webpage elements, respond to user actions, and build complex applications.


What are the features or powers of JavaScript?

JavaScript is known for its versatility and features such as:

  • Dynamic Typing: Variables can hold values of any data type without explicit declaration.
  • Prototype-based Object-Oriented: Objects inherit properties and methods directly from other objects.
  • Functions as First-Class Citizens: Functions can be assigned to variables, passed as arguments, and returned from other functions.
  • Asynchronous Programming: Supports non-blocking operations through callbacks, promises, and async/await.
  • Cross-platform Compatibility: Runs on all major web browsers and can be used for server-side development (Node.js).


What is a function?

In JavaScript, a function is a block of reusable code that performs a specific task when invoked. It can take parameters (inputs), perform actions, and return a value. Functions allow for code modularity, abstraction, and reusability. Here's a simple example:


// Function declaration
function greet(name) {
  return "Hello, " + name + "!";
}
// Function invocation
console.log(greet("John")); // Output: Hello, John!

Normal Function

 - Defined using the `function` keyword.

 - Has its own `this` context, which is determined by how it is called.

 - `arguments` variable available.

 - Cannot be used as constructors (cannot be invoked with `new`).

 - Suitable for methods and when `this` context is needed.


Arrow Function

 - Defined using the arrow `=>` syntax.

 - Lexical `this` context (inherits `this` from the surrounding code).

 - No `arguments` variable (but can use rest parameters `...args`).

 - Cannot be used as constructors.

 - More concise syntax, especially for short functions and callbacks.


// Normal Function
function greet(name) {
  return "Hello, " + name + "!";
}

// Arrow Function
const greetArrow = (name) => {
  return "Hello, " + name + "!";
}
console.log(greet("John")); // Output: Hello, John!
console.log(greetArrow("Jane")); // Output: Hello, Jane!


What Are Some Array Methods

forEach(): Executes a provided function once for each array element.

map(): Creates a new array by applying a function to each array element.

filter(): Creates a new array with elements that pass a test specified by a function.

find(): Returns the first element in an array that satisfies a provided testing function.

findIndex(): Returns the index of the first element in an array that satisfies a provided testing function.

some(): Checks if at least one element in the array satisfies a provided testing function.

every(): Checks if all elements in the array satisfy a provided testing function.

reduce(): Applies a function against an accumulator and each element in the array to reduce it to a single value.

reduceRight(): Applies a function against an accumulator and each value of the array (from right-to-left) to reduce it to a single value.

sort(): Sorts the elements of an array in place and returns the sorted array.

slice(): Returns a shallow copy of a portion of an array into a new array.

splice(): Changes the contents of an array by removing or replacing existing elements and/or adding new elements.

concat(): Returns a new array comprised of this array joined with other arrays and/or values.

includes(): Determines whether an array contains a certain element.

indexOf(): Returns the first index at which a given element can be found in the array, or -1 if it is not present.

lastIndexOf(): Returns the last index at which a given element can be found in the array, or -1 if it is not present.


What is the difference between `map` and `forEach`? 

  • map(): The map() method creates a new array by applying a function to each element of the original array. It returns a new array with the results of applying the function to each element.
  • forEach(): The forEach() method executes a provided function once for each array element. It does not return a new array; instead, it iterates over the elements of the array and applies the provided function to each element.


// Example using map()
const numbers = [1, 2, 3, 4, 5];
const doubledNumbers = numbers.map((num) => {
  return num * 2;
});
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]

// Example using forEach()
const numbers2 = [1, 2, 3, 4, 5];
let total = 0
numbers2.forEach((num) => {
  total += num;
});
console.log(total); // Output: 15


 What is the difference between `filter` and `find`? 

  • filter(): The filter() method creates a new array with all elements that pass a test implemented by the provided function. It returns an array containing all elements for which the callback function returns true.
  • find(): The find() method returns the value of the first element in the array that satisfies the provided testing function. It returns undefined if no matching element is found.


// Example using filter()
const numbers = [1, 2, 3, 4, 5];
const evenNumbers = numbers.filter((num) => {
  return num % 2 === 0;
});
console.log(evenNumbers); // Output: [2, 4]

// Example using find()
const people = [
  { name: 'John', age: 30 },
  { name: 'Alice', age: 25 },
  { name: 'Bob', age: 35 }
];
const alice = people.find((person) => {
  return person.name === 'Alice';

});

console.log(alice); // Output: { name: 'Alice', age: 25 }


Slice and Splice Method


  • slice(): The slice() method returns a shallow copy of a portion of an array into a new array. It does not modify the original array; instead, it returns a new array containing elements from the start index to the end index (excluding the end index).
  • splice(): The splice() method changes the contents of an array by removing or replacing existing elements and/or adding new elements in place. It modifies the original array and returns an array containing the removed elements.


// Example using slice()
const numbers = [1, 2, 3, 4, 5];
const slicedNumbers = numbers.slice(1, 4);
console.log(slicedNumbers); // Output: [2, 3, 4]
console.log(numbers); // Output: [1, 2, 3, 4, 5] (original array remains unchanged)

// Example using splice()
const fruits = ['apple', 'banana', 'cherry', 'date'];
const removedFruits = fruits.splice(1, 2, 'orange', 'pear');
console.log(removedFruits); // Output: ['banana', 'cherry'] (removed elements)
console.log(fruits); // Output: ['apple', 'orange', 'pear', 'date'] (original array modified)


What is clouser

Closure: In JavaScript, 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 finished executing. This allows the inner function to access variables and parameters from the outer function, even after the outer function has returned.


// Example demonstrating closure

function outerFunction() {
  const outerVariable = 'I am from outer function';
  function innerFunction() {
    console.log(outerVariable); // Accessing outerVariable from outer function's scope
  }
  return innerFunction;
}
const closureFunction = outerFunction();
closureFunction(); // Output: I am from outer function



What is hoisting in JavaScript?

  • Hoisting: In JavaScript, hoisting is a mechanism where variable declarations (but not initializations) and function declarations are moved to the top of their containing scope during the compilation phase, regardless of where they are declared in the code. This means that you can use a variable or a function before it is declared.
// Example demonstrating hoisting
console.log(x); // Output: undefined
var x = 5;
console.log(x); // Output: 5


In this example, even though the variable x is used before it is declared, JavaScript does not throw an error. This is because variable declarations are hoisted to the top of their containing scope during the compilation phase. So, the above code is essentially interpreted as:


var x; // Declaration is hoisted to the top
console.log(x); // Output: undefined
x = 5;
console.log(x); // Output: 5
example with let... const will show similar result
console.log(y); // Throws ReferenceError: Cannot access 'y' before initialization
let y = 10;
console.log(y); // Output: 10


What is asynchronous in JavaScript?

Asynchronous Programming: In JavaScript, asynchronous programming is a programming paradigm where operations can be performed independently of the main program flow. This allows tasks such as fetching data from a server, reading files, or waiting for user input to be handled without blocking the execution of other code. Asynchronous operations typically involve callbacks, promises, or async/await syntax to manage the flow of execution.

// Example demonstrating asynchronous programming with setTimeout
console.log('Start');
setTimeout(() => {
  console.log('Inside setTimeout callback');
}, 2000);
console.log('End');


 What is the difference between synchronous and asynchronous execution?

  • Synchronous Execution: In synchronous execution, code is executed sequentially, one line at a time, in the order it appears. Each line of code waits for the previous one to finish before executing.
  • Asynchronous Execution: In asynchronous execution, code doesn't wait for a task to finish before moving on to the next one. Instead, tasks are executed independently of the main program flow, allowing concurrent operations and non-blocking behavior.


 What is shallow copy and deep copy?


  • Shallow Copy: Shallow copy creates a new object or array and copies the references of the original object's properties or elements into the new object or array. If the original object contains nested objects or arrays, shallow copy only creates copies of the references to those nested objects or arrays, not the objects or arrays themselves.
  • Deep Copy: Deep copy creates a completely new object or array and recursively copies all nested objects or arrays within it. Each nested object or array is duplicated, resulting in an independent copy that is not affected by changes to the original object.


// Shallow Copy Example
const originalObject = { name: 'John', age: 30, hobbies: ['reading', 'swimming'] };
const shallowCopy = { ...originalObject };
originalObject.age = 35;
originalObject.hobbies.push('gardening');
console.log(originalObject); // Output: { name: 'John', age: 35, hobbies: ['reading', 'swimming', 'gardening'] }
console.log(shallowCopy); // Output: { name: 'John', age: 30, hobbies: ['reading', 'swimming', 'gardening'] }

Deep Copy example
// Original object
const original = {
 name: "John",
 address: {
  city: "New York",
  zip: "10001",
 },
};
// Deep copy using JSON methods
const deepCopy = JSON.parse(JSON.stringify(original));
// Modifying the nested object in the deep copy
deepCopy.address.city = "Los Angeles";
console.log(original.address.city); // Output: "New York" (Original object remains unchanged)
console.log(deepCopy.address.city); // Output: "Los Angeles"

What is temporal Dead Zone?

The Temporal Dead Zone (TDZ) is the period between a variable's declaration and its initialization when accessing the variable results in a ReferenceError. It occurs for variables declared with `let` and `const`, ensuring they are not accessed before being initialized.


What is Promises?

  • A Promise in JavaScript is an object representing the eventual completion or failure of an asynchronous operation. It is used for handling asynchronous operations and their results in a more manageable and intuitive way.
  • Promises can be in one of three states: pending (initial state), fulfilled (operation completed successfully), or rejected (operation failed).
  • Promises provide a cleaner alternative to callback functions for managing asynchronous code, enabling easier error handling and chaining of multiple asynchronous operations.


How do you handle promises in JavaScript?

To handle promises in JavaScript, you can use the then() method to handle the successful completion of the promise and the catch() method to handle any errors. Additionally, you can use the finally() method to execute code after the promise settles, regardless of its outcome.


Why We need Promises?

Promises are necessary in JavaScript for handling asynchronous operations cleanly, avoiding callback hell, simplifying error handling, chaining multiple operations, and synchronizing asynchronous tasks. They improve code readability, maintainability, and error management in modern JavaScript applications.


What is calllback Function?

  • Callback Function: In JavaScript, a callback function is a function that is passed as an argument to another function and is executed after a specific event or operation occurs. Callback functions are commonly used to handle asynchronous operations, such as fetching data from a server or responding to user input, by providing a way to execute code once the operation is complete.


// Example using a callback function defined separately and passed as a parameter
const numbers = [1, 2, 3, 4, 5];
// Callback function to double a number
const doubleNumber = (num) => {
  return num * 2;
};
// Using the map method with the callback function
const doubledNumbers = numbers.map(doubleNumber);
console.log(doubledNumbers); // Output: [2, 4, 6, 8, 10]


What Is Callback hell?

  • Callback Hell: Callback hell refers to the situation in JavaScript where multiple nested callback functions are used, resulting in deeply nested and hard-to-read code. This occurs when asynchronous operations are chained together using callback functions, leading to a pyramid-shaped structure of code.


// Example demonstrating callback hell
asyncOperation1((data1) => {
  asyncOperation2(data1, (data2) => {
    asyncOperation3(data2, (data3) => {
      // Nested callback functions continue...
    });
  });
});

What is DOM manipulation?

  • DOM Manipulation: DOM manipulation refers to the process of accessing, modifying, or updating the Document Object Model (DOM) of a web page using JavaScript. The DOM represents the structure and content of a web page as a tree-like structure of nodes, where each element, attribute, and text node is represented as an object. DOM manipulation allows developers to dynamically update the content, structure, and styling of a web page in response to user interactions, events, or data changes.
// Example demonstrating DOM manipulation
const element = document.getElementById('myElement'); // Accessing an element by its ID
element.textContent = 'Hello, world!'; // Modifying the text content of the element
element.style.color = 'blue'; // Updating the styling of the element


What is a higher-order function? Can you give an example? 

  • Higher-Order Function: In JavaScript, a higher-order function is a function that takes one or more functions as arguments or returns a function as its result. Essentially, it treats functions as first-class citizens, allowing them to be manipulated like any other value.


// Example of a higher-order function

function operate(operation, a, b) {
   return operation(a, b); // Calling the operation function with arguments

}
// Example functions for addition and subtraction
function add(a, b) {

   return a + b;
}
function subtract(a, b) {
   return a - b;
}
// Using the higher-order function with different operations
console.log(operate(add, 5, 3)); // Output: 8 (addition)
console.log(operate(subtract, 5, 3)); // Output: 2 (subtraction)


What Is ES6 module

  • ES6 Module: An ES6 module is a JavaScript file that allows you to organize code into reusable components, encapsulating functionality and data within a single unit. ES6 modules use the export and import keywords to define and import functionality between modules. Each module maintains its own scope, preventing pollution of the global namespace and promoting modularity and maintainability in JavaScript applications.


// Example of an ES6 module
// math.js - Exporting functionality
export const add = (a, b) => a + b;
export const subtract = (a, b) => a - b;
// app.js - Importing functionality
import { add, subtract } from './math.js';
console.log(add(5, 3)); // Output: 8
console.log(subtract(5, 3)); // Output: 2


 What is destructuring in JavaScript?

  • Destructuring: Destructuring is a feature in JavaScript that allows you to extract values from arrays or objects and assign them to variables in a concise and convenient way. It provides a shorthand syntax for extracting multiple values from complex data structures, such as arrays and objects, and assigning them to variables.




// Example of destructuring an array
const numbers = [1, 2, 3, 4, 5];
const [first, second, ...rest] = numbers;
console.log(first); // Output: 1
console.log(second); // Output: 2
console.log(rest); // Output: [3, 4, 5]

// Example of destructuring an object
const person = { name: 'John', age: 30, country: 'USA' };
const { name, age } = person;
console.log(name); // Output: John
console.log(age); // Output: 30


What are rest parameters in JavaScript? Where have you used them? 

Rest Parameters: Rest parameters are a feature in JavaScript that allows you to represent an indefinite number of arguments as an array. They provide a convenient way to handle functions with a variable number of arguments by collecting them into a single array parameter. Rest parameters are indicated by three dots (...) followed by the parameter name.


// Example of using rest parameters
function sum(...numbers) {
   return numbers.reduce((acc, num) => acc + num, 0);
}
console.log(sum(1, 2, 3)); // Output: 6
console.log(sum(1, 2, 3, 4, 5)); // Output: 15


setTimeOut vs SetInterval

  • setTimeout: The setTimeout function is a method in JavaScript that allows you to execute a function or code snippet after a specified delay, measured in milliseconds. It schedules the execution of the specified function once, after the specified delay, and then stops.
  • setInterval: The setInterval function is a method in JavaScript that allows you to repeatedly execute a function or code snippet at a specified interval, measured in milliseconds. It schedules the execution of the specified function repeatedly, with a fixed time interval between each execution.


What is the difference between local storage, session storage, and cookies?


  • Local Storage: Local storage is a web storage mechanism in modern web browsers that allows web applications to store data persistently on a user's computer. It provides a simple key-value storage interface and has no expiration date. Data stored in local storage remains available even after the browser is closed and reopened. It is typically used for storing user preferences, application state, or cached data.
  • Session Storage: Session storage is another web storage mechanism in modern web browsers that allows web applications to store data temporarily during a browser session. It provides a similar key-value storage interface to local storage but has a shorter lifespan. Data stored in session storage is cleared when the browser tab or window is closed, making it suitable for storing temporary session-specific data.
  • Cookies: Cookies are small pieces of data sent from a website and stored on a user's device by the web browser. They are primarily used to remember user preferences, authenticate users, and track user activity across different web pages or sessions. Cookies have an expiration date and can be either persistent (stored on the user's device for a specified period) or session-based (stored temporarily until the browser is closed). Unlike local storage and session storage, cookies have limitations on the amount of data that can be stored and are sent with every HTTP request, increasing network overhead.


. How can you fetch an API in JavaScript?

  • Fetching an API: To fetch data from an API in JavaScript, you can use the fetch function, which is built into modern web browsers. The fetch function makes an HTTP request to the specified URL and returns a promise that resolves to the response from the server. You can then use methods like json() to parse the response and work with the data.


// Example of fetching an API using async/await

async function fetchData() {
   try {
     const response = await fetch('https://api.example.com/data');
     if (!response.ok) {
       throw new Error('Failed to fetch data');
    }
     const data = await response.json();
     console.log(data); // Output: Retrieved data from the API
  } catch (error) {
     console.error('Error fetching data:', error.message);
  }
}
fetchData();


 What are the different types of loops in JavaScript and when would you use each one?

  • For Loop: Use when you know the exact number of iterations needed.
  • While Loop: Use when you don't know the exact number of iterations and want to loop based on a condition.
  • Do...While Loop: Similar to while loop, but guarantees at least one execution of the loop body.
  • For...In Loop: Use to iterate over object properties.
  • For...Of Loop: Use to iterate over iterable objects like arrays or strings.


 What is the difference between `==` and `===` in JavaScript? 

== (Equality Operator): Compares values after type coercion.

=== (Strict Equality Operator): Compares values without type coercion.


console.log(5 == '5'); // Output: true
console.log(0 == false); // Output: true
console.log(5 === '5'); // Output: false
console.log(0 === false); // Output: false


What is the `this` keyword in JavaScript and how does it behave in different contexts?


In JavaScript, the this keyword refers to an object.


Which object depends on how this is being invoked (used or called).


The this keyword refers to different objects depending on how it is used:

In an object method, this refers to the object.

Alone, this refers to the global object.

In a function, this refers to the global object.

In a function, in strict mode, this is undefined.

In an event, this refers to the element that received the event.

Methods like call(), apply(), and bind() can refer this to any object.


 What is a constructor function in JavaScript and how is it different from a regular function?

  • Constructor Function: In JavaScript, a constructor function is a special type of function that is used to create and initialize objects of a particular type (also known as instances). Constructor functions are typically used with the new keyword to create new object instances with properties and methods defined within the constructor function.



// Constructor Function
function Person(name, age) {
   this.name = name;
   this.age = age;
   this.greet = function() {
     console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  };
}

// Creating Object Instances
const person1 = new Person('John', 30);
const person2 = new Person('Alice', 25);
// Accessing Object Properties and Methods
console.log(person1.name); // Output: John
console.log(person2.age); // Output: 25
person1.greet(); // Output: Hello, my name is John and I am 30 years old.
person2.greet(); // Output: Hello, my name is Alice and I am 25 years old.



Difference from Regular FunctionThe key difference between a constructor function and a regular function lies in their intended usage and behavior. Constructor functions are specifically designed to create and initialize object instances, whereas regular functions are more general-purpose and can perform various tasks but do not necessarily create new object instances.


What is Data Types in javascript?

In JavaScript, data types represent the different kinds of values that can be manipulated and stored in variables. JavaScript has several data types that fall into two broad categories: primitive types and non-primitive (reference) types.


=>Primitive data types can store only a single value. To store multiple and complex values, non-primitive data types are used.


Special Notes

  • Typeof Operator: You can use the typeof operator to determine the type of a variable.
console.log(typeof 42);     // "number"
console.log(typeof 'hello');   // "string"
console.log(typeof true);    // "boolean"
console.log(typeof undefined);  // "undefined"
console.log(typeof null);    // "object" (this is actually a known bug in JavaScript)
console.log(typeof Symbol('id')); // "symbol"
console.log(typeof {});     // "object"
console.log(typeof []);     // "object"
console.log(typeof function(){}); // "function"




What is Prototype?

A prototype is a blueprint of an object. It allows objects to share properties and methods. When an object is created, it can inherit properties and methods from its prototype, even if those properties and methods do not exist directly on the current object. This mechanism is what enables JavaScript's inheritance.

var arr = [];
arr.push(2);
console.log(arr); // Outputs [2]


In the code above, as one can see, we have not defined any property or method called push on the array “arr” but the javascript engine does not throw an error.

The reason is the use of prototypes. As we discussed before, Array objects inherit properties from the Array prototype.

The javascript engine sees that the method push does not exist on the current array object and therefore, looks for the method push inside the Array prototype and it finds the method.

Whenever the property or method is not found on the current object, the javascript engine will always try to look in its prototype and if it still does not exist, it looks inside the prototype's prototype and so on. and this process is called prototype chaining


What are the types of errors in javascript?

There are two types of errors in javascript.

  1. Syntax error: Syntax errors are mistakes or spelling problems in the code that cause the program to not execute at all or to stop running halfway through. Error messages are usually supplied as well.
  2. Logical error: Reasoning mistakes occur when the syntax is proper but the logic or program is incorrect. The application executes without problems in this case. However, the output findings are inaccurate. These are sometimes more difficult to correct than syntax issues since these applications do not display error signals for logic faults


What is Recursion In Programing Language?

Recursion is a method where a function solves a problem by calling itself with smaller sub-problems until it reaches a simple base case. It’s useful for problems that can be broken down into smaller, similar problems, but care must be taken to ensure that the base case is reached to avoid infinite recursion.


recursion is a technique to iterate over an operation by having a function call itself repeatedly until it arrives at a result.


A recursive function typically has two main parts:

  1. Base Case: A condition that stops the recursion by providing a direct solution without further calls to itself.
  2. Recursive Case: The part of the function that reduces the problem into smaller instances and calls itself with these smaller instances.


function factorial(n) {
 if (n <= 1) { // Base case: factorial of 1 or 0 is 1
   return 1;
 } else {   // Recursive case: n * factorial of (n-1)
   return n * factorial(n - 1);
 }
}
console.log(factorial(5)); // 120


What is the use of a constructor function in javascript?

Constructor functions are used to create objects in javascript.

When do we use constructor functions?

If we want to create multiple objects having similar properties and methods, constructor functions are used.

Key Features of Constructor Functions

  1. Naming Convention: Constructor functions are typically named with a capital letter to distinguish them from regular functions.
  2. Using this: Inside the constructor function, this refers to the new object being created.
  3. Automatic Return: When called with new, the function automatically returns the newly created object.
// Constructor function for creating Person objects
function Person(name, age) {
 this.name = name;
 this.age = age;
 this.greet = function() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
 };
}
// Creating new Person objects using the constructor function
let alice = new Person('Alice', 30);
let bob = new Person('Bob', 25);
alice.greet(); // "Hello, my name is Alice and I am 30 years old."
bob.greet(); // "Hello, my name is Bob and I am 25 years old."


How Constructor Functions Work

  1. Creation of a New Object: When new Person('Alice', 30) is called, a new empty object is created.
  2. Setting this: The this keyword inside the Person function refers to this new object.
  3. Adding Properties and Methods: The properties (name and age) and the method (greet) are added to the new object.
  4. Returning the Object: The new object is returned automatically by the constructor function.


What Is DOM?

the Document Object Model (DOM) is a programming interface for web documents. It represents the structure of a document as a tree of objects, making it possible for programming languages like JavaScript to interact with and manipulate the content, structure, and style of web pages dynamically.


Key Points about the DOM:

1.Tree Structure:

  • The DOM represents a document as a tree of nodes. Each node corresponds to a part of the document, such as an element, attribute, or text.
  • The root of the tree is the document object, which provides access to the entire document.

2 .Node Types:

  • Element Nodes: Represent HTML tags (e.g., <div><p><a>).
  • Text Nodes: Contain the text content within elements.
  • Attribute Nodes: Represent the attributes of elements (e.g., classid).
  • Comment Nodes: Represent comments within the document.

3.Manipulation:

  • The DOM allows you to create, delete, modify, and rearrange elements and content.
  • Common methods for manipulation include document.createElement()element.appendChild()element.removeChild()element.setAttribute(), and element.innerHTML.

4.Traversal:

  • You can navigate the DOM tree using properties like parentNodechildNodesfirstChildlastChildnextSibling, and previousSibling.
  • Methods like getElementById()getElementsByClassName()getElementsByTagName()querySelector(), and querySelectorAll() are used to find and select elements.

5.Events:

  • The DOM provides an event model that allows you to listen for and respond to user interactions and other events.
  • Common event methods include addEventListener() and removeEventListener(), with events like clickmouseoverkeydown, and submit.

What is BOM

The Browser Object Model (BOM) is a concept in web development that refers to the objects provided by the web browser environment for interacting with the browser itself, outside of the content of the web page. While the DOM (Document Object Model) allows you to interact with and manipulate the content of a web page, the BOM allows you to interact with the browser.


<!DOCTYPE html>
<html lang="en">
<head>
  <meta charset="UTF-8">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>BOM Example</title>
</head>
<body>
  <h1>BOM Example</h1>
  <p id="currentUrl"></p>
  <button id="goToGoogle">Go to Google</button>
  <script>
    // Display the current URL
    document.getElementById('currentUrl').innerText = 'Current URL: ' + location.href;
    // Navigate to Google when the button is clicked
    document.getElementById('goToGoogle').addEventListener('click', function() {
      location.href = 'https://www.google.com';
    });
  </script>
</body>
</html>

What is the distinction between client-side and server-side JavaScript?

The distinction between client-side and server-side JavaScript lies in where the code is executed and what it is used for. Here's a simple breakdown:

Client-Side JavaScript

  • Execution: Runs in the browser.
  • Purpose: Creates interactive web pages, manipulates the DOM, and handles user events.
  • Examples: Form validation, animations, content updates.
  • Technologies: Vanilla JavaScript, jQuery, React, Angular, Vue.js.

Server-Side JavaScript

  • Execution: Runs on the server.
  • Purpose: Handles back-end logic like database interactions and user authentication.
  • Examples: HTTP request handling, database queries, form processing.
  • Technologies: Node.js, Express.js.


CLASS AND OBJECTS IN JS

What is class?

A class in JavaScript is a blueprint for creating objects. It defines properties and methods that the created objects will have. Classes in JavaScript are introduced in ES6 (ECMAScript 2015) and provide a more straightforward and structured way to create objects and handle inheritance


class Person {
 // Constructor method to initialize new objects
 constructor(name, age) {
   this.name = name;
   this.age = age;
 }
 // Method to greet
 greet() {
   console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
 }
}
// Creating an object using the class
const alice = new Person('Alice', 30);
alice.greet(); // "Hello, my name is Alice and I am 30 years old."

Object in JavaScript?

An object in JavaScript is a collection of related data and/or functionality, usually consisting of properties and methods. Objects are used to store and manipulate data in a structured way.


// Creating an object
const car = {
 brand: 'Toyota',
 model: 'Corolla',
 year: 2021,
 // Method to display car details
 displayDetails() {
   console.log(`Car: ${this.brand} ${this.model}, Year: ${this.year}`);
 }
};
car.displayDetails(); // "Car: Toyota Corolla, Year: 2021"


Which company developed JavaScript?

Netscape developed JavaScript and was created by Brenden Eich in the year of 1995.


Write a JavaScript code for adding new elements dynamically. 

<!DOCTYPE html>
<html lang="en">
<head>
  <title>Document</title>
</head>
<body>
  <button onclick="create()">
    Click Here!
  </button>
  <script>
    function create() {
       let geeks = document.createElement('geeks');
       geeks.textContent = "Geeksforgeeks";
       geeks.setAttribute('class', 'note');
       document.body.appendChild(geeks);
     }
  </script>
</body>
</html>

What do you mean by NULL in JavaScript?

 The NULL value represents that no value or no object. It is known as empty value/object.


 What is a prompt box?

 The prompt box is a dialog box with an optional message prompting the user to input some text. It is often used if the user wants to input a value before entering a page. It returns a string containing the text entered by the user, or null


How to submit a form using JavaScript?

You can use document.form[0].submit() method to submit the form in JavaScript.


How to convert the string of any base to integer in JavaScript?

In JavaScript, parseInt() function is used to convert the string to an integer. This function returns an integer of base which is specified in second argument of parseInt() function. The parseInt() function returns Nan (not a number) when the string doesn’t contain number.


Explain how to detect the operating system on the client machine?

To detect the operating system on the client machine, one can simply use navigator.appVersion or navigator.userAgent property. The Navigator appVersion property is a read-only property and it returns the string that represents the version information of the browser.


. What is the difference between innerHTML & innerText? 


innerHTML and innerText are properties used to manipulate the content of HTML elements, but they serve different purposes and behave differently.


innerHTML

  • PurposeinnerHTML gets or sets the HTML markup contained within an element.
  • Content: It includes all HTML tags and nested elements.
  • Usage:
  • Get: Returns the HTML content as a string, including tags.
  • Set: Parses a string as HTML and updates the element's content accordingly.
// Getting the HTML content
let element = document.getElementById("example");
console.log(element.innerHTML); // "<p>Hello <strong>World</strong></p>"
// Setting the HTML content
element.innerHTML = "This is a <strong>test</strong>.";
// The element now contains: This is a test. (with "test" in bold)


innerText

  • PurposeinnerText gets or sets the visible text content of an element, ignoring HTML tags.
  • Content: Only the text content, without any HTML tags.
  • Usage:
  • Get: Returns the text content, without HTML tags.
  • Set: Inserts text as plain text, escaping any HTML tags.
// Getting the text content
let element = document.getElementById("example");
console.log(element.innerText); // "Hello World"
// Setting the text content
element.innerText = "This is a <strong>test</strong>.";
// The element now contains: This is a <strong>test</strong>.
// (the tags are displayed as text)


 What is an event bubbling in JavaScript?

Consider a situation an element is present inside another element and both of them handle an event. When an event occurs in bubbling, the innermost element handles the event first, then the outer, and so on.


Explain passed by value and passed by reference.


From the above example, we can see that primitive data types when passed to another variable, are passed by value. Instead of just assigning the same address to another variable, the value is passed and new space of memory is created


we can see that while passing non-primitive data types, the assigned operator directly passes the address (reference).

function changeValue(val) {
  val = 100;
  console.log("Inside function:", val); // Inside function: 100
}
let num = 50;
console.log("Before function call:", num); // Before function call: 50
changeValue(num);
console.log("After function call:", num); // After function call: 50
function changeProperty(obj) {
  obj.value = 100;
  console.log("Inside function:", obj.value); // Inside function: 100
}
let myObj = { value: 50 };
console.log("Before function call:", myObj.value); // Before function call: 50
changeProperty(myObj);
console.log("After function call:", myObj.value); // After function call: 100