BRO_CODE Flashcards

1
Q

Arrow function?

A

A concise way to write function expressions, good for simple functions that you use only once (parameters) => some code. IN ARROW FUNCTION WE DON’T NECESSARILY NEED A ‘return’ STATEMENT IF WE HAVE ONLY ONE LINE OF CODE

(with an arrow function I have more than one line of code I need to add a set of curly braces after task)

function func1(callbackFunc){
    setTimeout(()=> {console.log("Task1");
        callbackFunc()}, 3000)
}

One line arrow function code

function func1(callbackFunc){
    setTimeout(()=> console.log("Task1"), 3000)
}
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
2
Q

WHAT IS Objects in JavaScript?

A
  1. What is an Object?
    An object is a collection of related properties (data) and methods (functions) that describe or represent something.OBJECT = A Collection of related properties and/ or methods
    Properties are what an object has
    Methods are function that an object can perform
    Properties are KEY AND VALUE PAIRS
    METHODS ARE FUNCTIONS THAT BELONG TO THE OBJECT
    Can represent real world objects(people, products, places)
    object = {key : value,
    key: function(){
    }💥Properties = What an object has (e.g., name, age)
    💥Methods = What an object can do (e.g., sayHello(), walk())
    Example: A person Objectconst person = {// PROPERTIES (data)firstName: “Patrick”,age: 30,isHappy: true,// METHOD (function)sayHello: function() {
     console.log("Hello!");
    }

};2. Accessing Properties & Methods💥Dot Notation (Most Common) console.log(person.firstName); // “Patrick”

person.sayHello(); // Calls the method → “Hello!”💥Bracket Notation (Useful for dynamic keys) console.log(person[“age”]); // 303. Real-World Example (SpongeBob Characters)//Let’s create a SpongeBob character object:

const spongebob = {

firstName: "SpongeBob",

lastName: "SquarePants",

age: 22,

job: "Fry Cook",

home: "Bikini Bottom",


// Method (action the object can do)

laugh: function() {

    console.log("HAHAHAHAHA!");
}

};

// Accessing properties

console.log(spongebob.firstName); // “SpongeBob”

// Calling a method

spongebob.laugh(); // “HAHAHAHAHA!”4. Why Use Objects?📚Organize related data & functions together (e.g., a user object with name, email, and login()).
📚Model real-world things (e.g., a car with color, speed, and drive()).
📚Avoid messy, separate variables (group them logically inside an object).5. Key Takeaways✅ Properties = Data (firstName, age)
✅ Methods = Functions (sayHello(), laugh())
✅ Objects group related things for cleaner code.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
3
Q

WHAT IS Constructors in JavaScript?

A

A constructor is a special function that creates and initializes an object instance of a class or an object type. It’s like a blueprint for creating multiple similar objects efficiently.1. Why Use Constructors?
Instead of manually creating each object like this:

const person1 = { name: “Alice”, age: 25 };
const person2 = { name: “Bob”, age: 30 };
const person3 = { name: “Charlie”, age: 35 };We can use a constructor function to automate the process:function Person(name, age){
this.name = name;
this.age = age; }
const person1 = new Person(“Alice”, 25);
const person2 = new Person(“Bob”, 30);
const person3 = new Person(“Charlie”, 35);Benefits:✔ Less repetitive code✔ Easier to manage multiple objects✔ Follows the DRY (Don’t Repeat Yourself) principle

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
4
Q

Static keyword

A

Static keyword that defines properties or methods that belong to A class itself, rather than objects created from that.
(class owns anything static, not the objects)
If you want access static properties access it by its class name

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

WHAT IS GETTER AND SETTER

A

In JavaScript, getters and setters are special methods that allow us to define how object properties are accessed and modified.
1. What is a Getter? A getter is a method that retrieves the value of a property. It allows us to access a property dynamically without directly exposing the internal value.
2. What is a Setter? A setter is a method that updates the value of a property. It allows us to add validation or transformations before assigning a new value.

**When and How Do You Use It? **

**Example 1: **

Basic Getter and Setter

class Person {
  constructor(name, age) {
    this._name = name; // Underscore to indicate private property
    this._age = age;
  }
  // Getter method
  get name() {
    return this._name;
  }
  // Setter method
  set name(newName) {
    if (newName.length > 2) {
      this._name = newName;
    } else {
      console.log("Name must be at least 3 characters long.");
    }
  }
}
const person = new Person("John", 25);
console.log(person.name); // Calls getter → "John"
person.name = "Al"; // Calls setter → "Name must be at least 3 characters long."
person.name = "Alex"; // Updates name
console.log(person.name); // "Alex"

**Example 2: Using Getters and Setters in Cypress (Test Automation) **

In test automation, getters and setters can be used for handling configurations dynamically.

class Config {
  constructor() {
    this._baseUrl = "https://example.com";
  }
  get baseUrl() {
    return this._baseUrl;
  }
  set baseUrl(newUrl) {
    if (newUrl.startsWith("https://")) {
      this._baseUrl = newUrl;
    } else {
      throw new Error("Invalid URL format");
    }
  }
}
const config = new Config();
cy.visit(config.baseUrl); // Uses getter to get the URL
config.baseUrl = "https://newsite.com"; // Updates base URL safely
cy.visit(config.baseUrl);

**Why Use Getters and Setters? **
Encapsulation: Protects internal data from direct modification.
Validation: Allows control over how data is set.
Computed Properties: Can return derived values dynamically.
Better Debugging & Maintainability.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
6
Q

CALLBACK FUNCTION?

A

CALLBACK FUNCTION 😄
✅ A function that is passed as an argument to another function
✅ Used to handle asynchronous operations:
1. Read a file
2. Network requests
3. Interacting with databases
“HEY, WHEN YOU’RE DONE, CALL THIS NEXT”
Of course! Let’s break down callback functions in a super easy and beginner-friendly way. 🚀

📞 What is a Callback Function?

A callback function is just a function that you pass to another function to be called later.

Think of it like this:

> “Hey, when you’re done with your task, call me back!”

That “call me back” function = callback

🧠 Why use it?

Because sometimes things take time (like loading data, or waiting 3 seconds), and we want to do something after that is finished.

📦 Simple Real-Life Example:

Let’s say you order pizza 🍕.

  1. You call the pizza shop (this is the main function).
  2. You say: “Call me when it’s ready” (that’s your callback).
  3. They make the pizza (takes time).
  4. When it’s ready, they call you back 📞 (your callback function runs).

💻 Code Version of That:

function callPizzaShop(callback) {
    console.log("Ordering pizza...");
    setTimeout(() => {
        console.log("Pizza is ready!");
        callback(); // call the callback function
    }, 3000); // wait 3 seconds
}
function answerThePhone() {
    console.log("Hello! I'm picking up the pizza!");
}

callPizzaShop(answerThePhone);

🖨 Output:

Ordering pizza...
(wait 3 seconds...)
Pizza is ready!
Hello! I'm picking up the pizza!

🧩 Key Points:

  • callback is a function passed as an argument.
  • It runs after something else finishes (like after 3 seconds).
  • It helps with asynchronous actions — waiting for something without blocking everything else.

✅ Visual Recap

function doSomething(callback) {
    // Do something first
    console.log("Doing something...");
    
    // Then call the callback
    callback();
}
function sayHi() {
    console.log("Hi from callback!");
}
doSomething(sayHi);

🖨 Output:

Doing something...
Hi from callback!
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

What is ERROR?

A

ERROR is an OBJECT that created to represent problem that occurs
Occurs often with user input or establishing a connection.
👩‍💻👨‍💻.

🧠 What is the Error object?

The Error object in JavaScript is used to represent something that went wrong in your code.

Think of it like a message container for when something fails.

const error = new Error("Something went wrong!");
console.log(error.name);   // Error
console.log(error.message); // Something went wrong!

✅ Why is it useful?

  • It tells you what went wrong
  • It gives a message and a stack trace
  • It helps you debug issues
  • You can use it to simulate errors in tests

📦 Structure of an Error Object

|————–|————————————-|
| message | Description of the error |
| stack | Where the error happened (call trace) |

🔥 Example: Throwing and Catching an Error

try {
  throw new Error("API failed to respond");
} catch (err) {
  console.log(err.name);     // "Error"
  console.log(err.message);  // "API failed to respond"
  console.log(err.stack);    // shows file and line where error occurred
}

🧪 Use in Testing (Cypress or Unit Tests)

You might simulate or test for errors like this:

✅ Check for error messages in UI

cy.get('.error-message').should('contain', 'Something went wrong');

✅ Mock an error in API response

cy.intercept('GET', '/api/data', {
  statusCode: 500,
  body: { error: 'Internal Server Error' }
}).as('getData');

✅ Custom error for logic validation

function divide(a, b) {
  if (b === 0) throw new Error("Cannot divide by zero");
  return a / b;
}
try {
  divide(10, 0);
} catch (err) {
  console.log(err.message); // "Cannot divide by zero"
}

🎯 Summary

| Property | Description |

| name | The type of error (e.g., "Error", "TypeError") |

Feature | Explanation |
|——————–|————————————————–|
| new Error(message) | Create an error with a message |
| throw | Manually trigger an error |
| try...catch | Handle or test what happens when an error occurs |
| Use in tests | Simulate failures, check error messages |

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

WHAT IS PROMISE

A

Promises

  • What they are: A Promise is an object representing the eventual completion (or failure) of an asynchronous operation and its resulting value. Think of it as a placeholder for a value you don’t have yet.
  • States: A Promise can be in one of three states:
    • pending: The initial state; the operation hasn’t completed yet.
    • fulfilled: The operation completed successfully, and the Promise now has a resolved value.
    • rejected: The operation failed, and the Promise has a reason for the failure (an error).
  • How you use them: You attach callbacks using the .then() method for handling fulfillment and the .catch() method for handling rejection. You can chain .then() calls to perform sequential asynchronous operations.
  • Syntax Example:```
    function fetchData() {
    return new Promise((resolve, reject) => {
    // Simulate an asynchronous operation (e.g., fetching data from an API)
    setTimeout(() => {
    const success = Math.random() > 0.5; // Simulate success or failure
    if (success) {
    resolve({ data: ‘Here is your data!’ });
    } else {
    reject(new Error(‘Failed to fetch data.’));
    }
    }, 1000);
    });
    }// Using the Promise
    console.log(‘Starting data fetch…’);
    fetchData()
    .then(result => {
    console.log(‘Success:’, result.data);
    // You can chain more async operations here
    return ‘Processed: ‘ + result.data;
    })
    .then(processedResult => {
    console.log(‘Further processing:’, processedResult);
    })
    .catch(error => {
    console.error(‘Error:’, error.message);
    })
    .finally(() => {
    console.log(‘Fetch attempt finished.’);
    });
    console.log(‘Promise initiated…’); // This logs before the promise resolves/rejects
    ```
  • Potential Drawback: For complex sequences of asynchronous operations, chaining multiple .then() calls can sometimes lead to code that’s harder to read and follow (sometimes referred to as “Promise chaining” which, while better than “callback hell”, can still be complex). Error handling with .catch() is specific to the Promise chain.

Feature | Promise (.then/.catch) | async/await |

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
9
Q

WHAT IS ASYNC AND AWAIT

A

Async/Await

  • What they are: Keywords that provide a way to write asynchronous Promise-based code as if it were synchronous.
    • async: Used to declare a function as asynchronous. An async function always implicitly returns a Promise. If the function returns a value, the Promise resolves with that value. If the function throws an error, the Promise rejects with that error.
    • await: Used inside an async function to pause the execution of that function until a Promise settles (is either fulfilled or rejected). If the Promise fulfills, await returns the fulfilled value. If the Promise rejects, await throws the rejection reason (which you typically catch with try...catch).
  • How you use them: You mark the function containing asynchronous operations with async. Inside that function, you use await before any function call that returns a Promise you need to wait for. You use standard try...catch...finally blocks for error handling.
  • Syntax Example (equivalent to the Promise example):```
    function fetchData() { // Same Promise-returning function as before
    return new Promise((resolve, reject) => {
    setTimeout(() => {
    const success = Math.random() > 0.5;
    if (success) {
    resolve({ data: ‘Here is your data!’ });
    } else {
    reject(new Error(‘Failed to fetch data.’));
    }
    }, 1000);
    });
    }// Using async/await
    async function processData() {
    console.log(‘Starting data fetch…’);
    try {
    const result = await fetchData(); // Pauses here until fetchData promise resolves/rejects
    console.log(‘Success:’, result.data);
      const processedResult = 'Processed: ' + result.data;
      console.log('Further processing:', processedResult);
    
    } catch (error) {
      console.error('Error:', error.message);
    } finally {
      console.log('Fetch attempt finished.');
    }   }
    processData();
    console.log(‘Async function initiated…’); // This logs almost immediately
    ```
  • Advantages: The code often looks cleaner, more linear, and easier to read because it resembles synchronous code structure. Error handling uses standard try...catch, which is familiar to many developers.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

Async and await VS Promises

A

Okay, let’s break down the differences between Promise and async/await in JavaScript.

The most crucial thing to understand is that async/await is built on top of Promises. It’s essentially “syntactic sugar” – a cleaner, more readable way to write asynchronous code that uses Promises behind the scenes. They aren’t competing concepts; rather, async/await is an enhancement for working with Promises.

Here’s a breakdown:
Key Differences Summarized:

In modern JavaScript development, async/await is generally preferred for writing asynchronous code due to its readability and simpler error handling, but it’s essential to understand Promises because async/await relies entirely on them.

:—————- | :——————————————- | :—————————————————- |
| Core Nature | An object representing a future value. | Keywords for handling Promises with cleaner syntax. |
| Syntax | Uses .then(), .catch(), .finally() methods. | Uses async keyword for functions, await for waiting. |
| Code Flow | Callback-based, chaining leads execution flow. | Looks synchronous, linear execution flow (within the async function). |
| Readability | Can become complex with deep chaining. | Generally considered more readable and intuitive. |
| Error Handling| Uses .catch() blocks attached to the chain. | Uses standard try...catch...finally blocks. |
| Underlying Tech| The fundamental mechanism. | Syntactic sugar built upon Promises. |
| Return Value | .then returns a new Promise. | async function always returns a Promise. |

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
11
Q

JavaScript дахь hoisting

A

JavaScript дахь hoisting (өргөлт) гэдэг нь хувьсагч эсвэл функцийн тодорхойлолтыг кодын гүйцэтгэлээс өмнө тухайн хүрээний (scope) дээд хэсэгт “өргөж” hoisting байршуулах үйлдэл юм. Энэ нь зөвхөн тодорхойлолт (declaration)-д хамаарна, утга оноолт (assignment) биш.

Онцлог:
- Функцын тодорхойлолт: function түлхүүр үгээр тодорхойлогдсон функцууд бүрэн өргөгддөг hoisting (тодорхойлолт болон бие хамт).
- Хувьсагчийн тодорхойлолт: var, let, const-оор тодорхойлогдсон хувьсагчид хэсэгчлэн өргөгддөг hoisting хийгддэг . var нь undefined болж өргөгддөг hoisting хийгддэг бол let/const нь “Temporal Dead Zone” (TZD)-д ордог тул тодорхойлогдохоос өмнө хандахад алдаа гарна.
- Функцын илэрхийлэл: Зөвхөн хувьсагчийн тодорхойлолт өргөгддөг, функцын бие биш.

Жишээ:

javascript
console.log(myVar); // undefined (өргөгдсөн **hoisting**  хийгдсэн гэхдээ утга оноогдоогүй)
var myVar = 5;

sayHello(); // "Сайн байна уу!" (функц бүрэн өргөгдсөн)
function sayHello() {
    console.log("Сайн байна уу!");
}

console.log(funcExpr); // undefined (зөвхөн хувьсагч өргөгдсөн)
var funcExpr = function() {
    console.log("Функцын илэрхийлэл");
};

Яагаад ийм байдаг вэ?
JavaScript-ийн хөрвүүлэгч кодыг гүйцэтгэхээс өмнө тодорхойлолтыг уншиж, хүрээнд байршуулдаг. Энэ нь кодын уян хатан байдлыг хангадаг ч let/const ашиглан TZD-ийн тусламжтайгаар алдааг багасгахыг зөвлөдөг.

Эндээс hoisting-ийн гол санаа нь кодын тодорхойлолтыг дээш “зөөж” гүйцэтгэх явдал юм, гэхдээ var-аас илүү let/const ашиглах нь илүү аюулгүй бөгөөд орчин үеийн практикт нийцдэг.

How well did you know this?
1
Not at all
2
3
4
5
Perfectly
12
Q

GETTER AND SETTER

A

JavaScript getters and setters are special methods that control how you access and modify object properties.

We use them because:

  • Setters allow us to validate data before it’s assigned to a property, ensuring data integrity.
  • They help with encapsulation, hiding internal implementation details.
  • They let us add extra logic (like calculations or logging) when getting or setting a property.
  • Getters can create computed properties whose values are dynamically calculated.

Essentially, they give us more control over property access and modification compared to directly accessing properties.

class Person {
  constructor(name, age) {
    this._name = name; // Underscore to indicate private property
    this._age = age;
  }

  // Getter method
  get name() {
    return this._name;
  }

  // Setter method
  set name(newName) {
    if (newName.length > 2) {
      this._name = newName;
    } else {
      console.log("Name must be at least 3 characters long.");
    }
  }
}

const person = new Person("John", 25);
console.log(person.name); // Calls getter → "John"
person.name = "Al"; // Calls setter → "Name must be at least 3 characters long."
person.name = "Alex"; // Updates name
console.log(person.name); // "Alex",
How well did you know this?
1
Not at all
2
3
4
5
Perfectly