DEV Community

Cover image for notes for phase 1 project review 1-1
chimichimi123
chimichimi123

Posted on

notes for phase 1 project review 1-1

1
API (Application Programming Interface):

  • An API is a set of rules and protocols that allows different software applications to communicate with each other. It defines the methods and data formats that applications can use to request and exchange information.

2
ES (ECMAScript):

  • ES stands for ECMAScript, which is the standardized specification for the scripting language JavaScript. When we refer to ES5, ES6, etc., we are referring to different versions of the ECMAScript specification.

3
Current ES version:

  • The current ECMAScript version is ES14, which was finalized in June 2023.

4
Major features introduced in ES6:

  • Arrow functions

  • Classes

  • Template literals

  • Let and const declarations

  • Enhanced object literals

  • Destructuring assignment

  • Default parameters

  • Spread and rest operators

  • Promises

  • Modules

5
Differences between let, const, and var:

  • var has function scope or global scope, while let and const have block scope.

  • Variables declared with var can be redeclared and reassigned, while variables declared with let can be reassigned but not redeclared, and variables declared with const cannot be reassigned or redeclared.

  • const must be initialized during declaration, while let and var can be declared without initialization.

  • let and const are hoisted to the top of their block scope, but they are not initialized until their declaration is evaluated. This is known as the "temporal dead zone."

6
Differences between arrow functions and regular functions:

  • Arrow functions do not have their own this, arguments, super, or new.target bindings, whereas regular functions do.

  • Arrow functions cannot be used as constructors with the new keyword.

  • Arrow functions have a more concise syntax compared to regular functions.

7
Function expressions:

  • Function expressions are functions that are assigned to variables or passed as arguments to other functions.

  • They can be named or anonymous.

8
Converting arrow function to function declaration:

Arrow function:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

Function declaration:

function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

9
Converting function declaration to arrow function:

Function declaration:

function add(a, b) {
  return a + b;
}
Enter fullscreen mode Exit fullscreen mode

Arrow function:

const add = (a, b) => a + b;
Enter fullscreen mode Exit fullscreen mode

10
Callback function:

  • A callback function is a function that is passed as an argument to another function and is executed after some operation has been completed.

Example in project:

fetchData(url, (data) => {
  console.log(data);
});
Enter fullscreen mode Exit fullscreen mode

11
Hoisting:

  • Hoisting is a JavaScript mechanism where variables and function declarations are moved to the top of their containing scope during the compile phase, before the code execution.

Example:

console.log(x); // Output: undefined
var x = 5;
Enter fullscreen mode Exit fullscreen mode

12
Closure:

  • A closure is the combination of a function and the lexical environment within which that function was declared. It allows a function to access and manipulate variables from its parent scope even after the parent function has finished executing.

13
Object.assign():

  • Object.assign() is used to copy the values of all enumerable own properties from one or more source objects to a target object. It returns the target object.

14
Array methods:

  • .map(): Creates a new array populated with the results of calling a provided function on every element in the calling array.

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

  • .filter(): Creates a new array with all elements that pass the test implemented by the provided function.

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

  • .reduce(): Executes a reducer function on each element of the array, resulting in a single output value.

15
Keyword this and context:

  • The this keyword refers to the object it belongs to. In the global context, this refers to the global object (e.g., window in browsers).

  • In JavaScript, the value of this is determined by how a function is called (the execution context).

Example:

const obj = {
  name: "John",
  greet: function() {
    console.log(`Hello, ${this.name}!`);
  }
};
obj.greet(); // Output: Hello, John!
Enter fullscreen mode Exit fullscreen mode

16
Destructuring:

  • Destructuring is a JavaScript expression that allows extracting data from arrays, objects, and nested structures into distinct variables.

Example:

const { name, age } = person;
Enter fullscreen mode Exit fullscreen mode

17
Rest/spread operator:

  • The rest parameter (...) allows a function to accept an indefinite number of arguments as an array.

  • The spread operator (...) allows an array expression or string to be expanded in places where zero or more arguments or elements are expected.

Example:

const arr = [1, 2, 3];
const newArr = [...arr, 4, 5, 6]; // Spread operator
Enter fullscreen mode Exit fullscreen mode

18
Event listeners

  • Event listeners are functions that wait for a specific event to occur and then execute a predefined action. In JavaScript, event listeners are attached to DOM elements, and they listen for events such as clicks, keypresses, mouse movements, etc. When the specified event occurs on the element, the listener executes the associated callback function.

19
preventDefault()

  • preventDefault() is a method used to prevent the default action of an event from occurring. It is typically called within event handlers to stop the browser's default behavior associated with a particular event. For example, calling preventDefault() on a click event prevents the default action of following a link or submitting a form.

  • preventDefault() can be used with various types of events, including click events, submit events, keypress events, etc.

20
stopPropogation()

  • stopPropagation() is a method used to stop the propagation of an event through the DOM tree. When an event occurs on a DOM element, it typically "bubbles" up through its ancestors, triggering event handlers on each ancestor element. Calling stopPropagation() prevents this bubbling process, so the event will not trigger any further event handlers.

  • stopPropagation() can be used with events that bubble, such as click events, mouse events, key events, etc.

21
Asynchronous code

  • Asynchronous code in JavaScript allows certain operations to be executed independently of the main program flow. This means that while an asynchronous operation is being performed, other code can continue to execute without waiting for the asynchronous operation to complete. Asynchronous operations are commonly used for tasks such as fetching data from a server, reading files, or waiting for user input.

Some examples of functions/methods that behave asynchronously include:

  • setTimeout(): Executes a function after a specified delay.

  • fetch(): Initiates a network request and returns a promise that resolves with the response.

  • XMLHttpRequest: Performs asynchronous HTTP requests.

  • addEventListener(): Listens for events asynchronously.

22
Fetch

  • The fetch() function is used to make HTTP requests to servers. It returns a promise that resolves to the Response object representing the response to the request. This Response object contains information such as the status of the response, headers, and the response body.

23
Promise

  • A promise is an object that represents the eventual completion or failure of an asynchronous operation and its resulting value. Promises are used to handle asynchronous operations in JavaScript, allowing you to write cleaner and more maintainable code.

24
.then() after fetch

  • We use the .then() method after a fetch request to handle the response from the server once it becomes available. .then() is a method of promises, and it is used to specify what should happen after a promise is resolved (i.e., when the asynchronous operation completes successfully). Inside the .then() method, you provide a callback function that receives the resolved value of the promise as its argument.

25
What other methods does a promise object respond to?

Besides .then() and .catch(), promise objects also respond to methods such as:

  • .finally(): Executes a callback function after the promise is settled (either resolved or rejected).

  • .all(): Combines multiple promises into a single promise that resolves when all of the input promises have resolved.

  • .race(): Returns a promise that resolves or rejects as soon as one of the input promises resolves or rejects.

26
.JSON() function

  • The .json() function is a method used with the fetch() API to parse the JSON-encoded response body. When a request is made using fetch(), the response object contains a method called .json(), which returns a promise. This promise resolves with the JSON representation of the response body after it has been parsed.

EXAMPLE

fetch('https://api.example.com/data')
  .then(response => response.json())
  .then(data => {
    // Process the parsed JSON data
    console.log(data);
  })
  .catch(error => {
    // Handle errors
    console.error('Error fetching data:', error);
  });
Enter fullscreen mode Exit fullscreen mode

27
JSON.stringify() purpose

  • The purpose of JSON.stringify() is to convert a JavaScript object or value to a JSON string. It serializes the object into a JSON-formatted string representation that can be transmitted over a network or stored in a file. Some use cases include sending data to a server, saving data locally, or transferring data between different parts of an application.

EXAMPLE

const obj = { name: 'John', age: 30 };
const jsonString = JSON.stringify(obj);
console.log(jsonString); // Output: '{"name":"John","age":30}'
Enter fullscreen mode Exit fullscreen mode

Some of the unsupported data types in JSON.stringify() include:

  • Functions: Functions cannot be represented in JSON format because JSON is a data format, and functions are executable code.

  • Undefined: undefined values are not allowed in JSON. If a property in an object has the value undefined, it will be omitted during serialization.

  • Symbols: Symbols are also not supported in JSON, as they are JavaScript-specific constructs that don't have a representation in JSON.

  • Circular references: Objects with circular references (where one property refers back to the same object) cannot be serialized to JSON, as JSON does not support cyclical data structures. Attempting to stringify an object with circular references will result in an error or an incomplete serialization.

28
does JS have classes

  • Yes, JavaScript has classes since the introduction of ES6 (ECMAScript 2015). Here's how you can create a class in JavaScript.

EXAMPLE

class Person {
  constructor(name, age) {
    this.name = name;
    this.age = age;
  }

  greet() {
    console.log(`Hello, my name is ${this.name} and I am ${this.age} years old.`);
  }
}

const john = new Person('John', 30);
john.greet(); // Output: Hello, my name is John and I am 30 years old.
Enter fullscreen mode Exit fullscreen mode

29
purpose of constructor function

  • The purpose of the constructor function in JavaScript classes is to initialize object instances with specific values. It is automatically called when a new object is created from the class.

30
How to make an object method in JS

  • To create an object method in JavaScript, you can simply define a function within the class:

EXAMPLE

class MyClass {
  myMethod() {
    // Method implementation
  }
}
Enter fullscreen mode Exit fullscreen mode

31
how to make a class method/function in JS

  • To create a class method or function in JavaScript, you use the static keyword:

EXAMPLE

class MyClass {
  static myMethod() {
    // Method implementation
  }
}

MyClass.myMethod(); // Calling the class method
Enter fullscreen mode Exit fullscreen mode

32
How to make a property/method private in ES6

  • To make a property or method private in ES6, you can use closures and the concept of encapsulation. By defining variables or functions within the constructor using let or const, they become accessible only within the scope of the constructor and are effectively private:

EXAMPLE

class MyClass {
  constructor() {
    let privateVariable = 'This is private';

    this.getPrivateVariable = function() {
      return privateVariable;
    };
  }
}
Enter fullscreen mode Exit fullscreen mode

33
How to transform your OOJS code into functional code

  • To transform object-oriented JavaScript code into functional code, you would typically use functions and closures to encapsulate data and behavior. Instead of defining classes and methods, you would define functions that operate on data. Functional programming emphasizes immutability and pure functions, which can lead to more predictable and maintainable code. However, the approach may vary depending on the specific requirements and design preferences.

Top comments (0)