Skip to content

Latest commit

 

History

History
267 lines (197 loc) · 11.1 KB

1.Basics_Fundamentals-II.md

File metadata and controls

267 lines (197 loc) · 11.1 KB

100 JS Questions (Basics-II)

Q1. What is a loop? What are the types of loops in JS?

A loop is a programming way to run a piece of code repeatedly until a certain condition is met.

Loop Type Definition Syntax Example
for Executes a block of code a specified number of times. for (initialization; condition; increment/decrement) { // code to be executed } for (let i = 0; i < 5; i++) { console.log(i); }
while Executes a block of code as long as a specified condition is true. while (condition) { // code to be executed } let x = 0; while (x < 5) { console.log(x); x++; }
do-while Executes a block of code at least once, then repeats as long as a specified condition is true. do { // code to be executed } while (condition); let x = 0; do { console.log(x); x++; } while (x < 5);
for...of Iterates over the elements of an iterable object (e.g., arrays, strings). for (let element of iterable) { // code to be executed } let fruits = ["apple", "banana", "cherry"]; for (let fruit of fruits) { console.log(fruit); }
for...in Iterates over the properties of an object. for (let property in object) { // code to be executed } let person = { name: "Alice", age: 30 }; for (let prop in person) { console.log(prop + ": " + person[prop]); }

Q2. What are Functions in JS? What are the types of functions?

A funation is a reusable block of code that performs a specific task.

function sum(a,b){
    let c=a+b
    return c;
}

result = sum(5, 10);

// function keyword: function
// function name: sum
// parameter list: (a,b)
// function body: let c = a+b; return c;
// function call: sum()
// argument list: 5,10
Type of Function Definition Syntax Example
Named Function A function with a specific name. function functionName() { // code } function greet() { console.log("Hello!"); }
Anonymous Function A function without a name. function() { // code } let greet = function() { console.log("Hello!"); };
Function Expression A function assigned to a variable. let functionName = function() { // code }; let greet = function() { console.log("Hello!"); };
Arrow Function A concise way to define functions using arrow syntax. const functionName = () => { // code }; const greet = () => console.log("Hello!");
IIFE (Immediately Invoked Function Expression) A function that is defined and executed immediately. (function() { // code })(); (function() { console.log("Hello!"); })();
Callback Function A function passed as an argument to another function. function outerFunction(callback) { callback(); } function greet() { console.log("Hello!"); } outerFunction(greet);
Higher-Order Function A function that takes another function as an argument or returns a function. function higherOrderFunction(callback) { // ... } function add(x, y) { return x + y; } function applyOperation(callback, a, b) { return callback(a, b); }

Q3. What are Arrow Functions in JS? What is its use? V.IMP.

Arrow functions also known as fat arrow functions, is a simpler and shorter way for defining functions in JavaScript.

// Traditional approach

function add(x, y)
{
    return x+y;
}

console.log(add(5, 3));
//output: 8


// Arrow function

const add = (x, y) => x + y;

console.log(add(5, 3));
//output: 8

Q4. What are Arrays in JS? How to get, add & remove elements from arrays?

An array is a data type that allows you to store multiple values in a single variable.

Get Add Remove Modify Others
indexOf() push() pop() map() join()
find() concat() shift() forEach() length
filter() splice() sort() reduce()
slice() reverse() some()
every()

Get

Category Method Definition Syntax Example
Get indexOf() Returns the index of the first occurrence of an element in an array. array.indexOf(element) let fruits = ["apple", "banana", "cherry"]; let index = fruits.indexOf("banana");
Get find() Returns the first element in an array that satisfies the provided testing function. array.find(callback) let numbers = [1, 2, 3, 4, 5]; let result = numbers.find(x => x > 3);
Get filter() Returns a new array containing elements that satisfy the provided testing function. array.filter(callback) let numbers = [1, 2, 3, 4, 5]; let evenNumbers = numbers.filter(x => x % 2 === 0);
Get slice() Returns a new array containing a portion of the original array. array.slice(start, end) let fruits = ["apple", "banana", "cherry", "date"]; let slicedFruits = fruits.slice(1, 3);

Add

Category Method Definition Syntax Example
Add push() Adds one or more elements to the end of an array and returns the new length. array.push(element1, element2, ...) let fruits = ["apple", "banana"]; fruits.push("cherry", "date");
Add concat() Returns a new array that is the concatenation of two or more arrays. array1.concat(array2, array3, ...) let array1 = [1, 2]; let array2 = [3, 4]; let newArray = array1.concat(array2);

Remove

Category Method Definition Syntax Example
Remove pop() Removes the last element from an array and returns it. array.pop() let fruits = ["apple", "banana", "cherry"]; let removedFruit = fruits.pop();
Remove shift() Removes the first element from an array and returns it. array.shift() let fruits = ["apple", "banana", "cherry"]; let removedFruit = fruits.shift();
Remove splice() Removes elements from an array and optionally inserts new elements. array.splice(start, deleteCount, item1, item2, ...) let fruits = ["apple", "banana", "cherry"]; fruits.splice(1, 1, "orange");

Modify

Category Method Definition Syntax Example
Modify map() Creates a new array with the results of calling a provided function on every element in the original array. array.map(callback) let numbers = [1, 2, 3, 4, 5]; let squaredNumbers = numbers.map(x => x * x);
Modify forEach() Calls a provided function once for each element in the array. array.forEach(callback) let fruits = ["apple", "banana", "cherry"]; fruits.forEach(fruit => console.log(fruit));
Modify sort() Sorts the elements of an array in place. array.sort(compareFunction) let numbers = [3, 1, 4, 2]; numbers.sort();
Modify reverse() Reverses the elements of an array in place. array.reverse() let fruits = ["apple", "banana", "cherry"]; fruits.reverse();

Others

Category Method Definition Syntax Example
Others join() Joins the elements of an array into a string. array.join(separator) let fruits = ["apple", "banana", "cherry"]; let fruitsString = fruits.join(", ");
Others length Returns the length of an array. array.length let fruits = ["apple", "banana", "cherry"]; let length = fruits.length;
Others reduce() Applies a function to each element in the array, reducing it to a single value. array.reduce(callback, initialValue) let numbers = [1, 2, 3, 4, 5]; let sum = numbers.reduce((acc, cur) => acc + cur, 0);
Others some() Tests whether at least one element in the array passes the provided testing function. array.some(callback) let numbers = [1, 2, 3, 4, 5]; let hasEvenNumber = numbers.some(x => x % 2 === 0);
Others every() Tests whether all elements in the array pass the provided testing function. array.every(callback) let numbers = [2, 4, 6, 8]; let allEven = numbers.every(x => x % 2 === 0);

image

Q5. What are Objects in JS? V.IMP.

An object is a data type that allows you to store key-value pairs.

Object:

  • String / number / boolen / null / undefined
  • Array
  • Function
  • Object
//Object Example
let person = {
  name: "Happy",
  hobbies: ["Teaching", "Football", "Coding"],
  greet: function() {
    console.log("Name: " + this.name);
  }
};

console.log(person.name); // Output: "Happy"
console.log(person.hobbies[1]); // Output: "Football"
person.greet(); // Output: "Name: Happy"

Q6. What is Scope in JavaScript? V.IMP.

Scope determines where variables are defined and where they can be accessed.

//Global = accessbile anyhere
let globalVariable = "global";

greet();

function greet() {
  //Function - accessbile inside function only
  let functionVariable = "function";

  if (true) {
    // Block - accessible inside block only
    let blockVariables = "block";

    console.log(blockVariables); // Output: block
    console.log(functionVariable); // Output: function
    console.log(globalVariable); // Output: global
  }

  console.log(functionVariable); // Output: function
  console.log(globalVariable); // Output: global
}

console.log(gloveredVariable); // Output: global

Q7. What is Hoisting in JavaScript? V.IMP.

Hoisting is a JavaScript behavior where functions and variable declarations are moved to the top of their respective scopes during the complilation phase.

Hoisting

  • Function hoisting
  • Variable hoisting
Feature Function Hoisting Variable Hoisting
Behavior Functions are moved to the top of their scope during compilation. Variable declarations are moved to the top of their scope during compilation, but their assignments are not.
//Function hoisting
myFunction();

function myFunction() {
  console.log("Hello!");
}

//Output: Hello
//Varibale hoisting
x = 10;
console.log(x); 
// Output: 10

var x;

Q8. What is Error Handling in JS?

Error handling is the process of managing errors

// try block contains the code that might throw an error
try {
  const result = someUndefinedVariable + 10; // This line will throw an error because someUndefinedVariable is not defined
  console.log(result);
} catch (error) {
  // catch block is where the error is handled
  console.log('An error occurred:', error.message);
}

// Output:
// An error occurred: someUndefinedVariable is not defined

Q9. What is JSON?

Q10. What is asynchronous programming in JS? What is its use? V.IMP.

Asynchronous programming allows multiple tasks or operations to be initiated and executed concurrently. Asynchronous operations do not block the execution of the code.

Use of Asynchronous Operations

  • Fetching Data from API
  • Downloading Files
  • Uploading Files
  • Animations and Transitions
  • Time taking operations
// Synchronous Programming
// Not efficient

console.log("Start");

Function1(); // Function 1 is called before Function 2, even though it might be time-consuming
Function2();

console.log("End");

// Time taking function
function Function1() {
  // Loading Data from an API
  // Uploading Files
  // Animations
}

function Function2() {
  console.log(100 + 50);
}