Miscallaneous 5 Flashcards

1
Q

x to the power of 2

A

x ** 2 is equivalent to Math.pow(x, 2)

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

32 bit signed integer

A
  • The largest value it can represent is (2^31) - 1.
  • The smallest value it can represent is -(2^31).

https://www.computerhope.com/jargon/num/32bit.htm

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

What are react hooks?

Describe 2 main

A

useEffect is a f, lets do side effects in functional components, takes in 2 arguments, a function, and an array. The f decides which side effect to run, and array decides when to resinc or rerun the array.

https://ui.dev/why-react-hooks/ this is history of react, pretty complex, do this after going through the oop with mosh

es6 introduced class declarations, way to natively build classes in js, which you could use to create components - use constructor to add state to component; as a state property on the instance

class fields allows to add instance properties directly as property to the class without having to use constructor
=======
* react hooks in functional components for state manangement and lifecycle hooks to replace class based components

useState is an array returning a state and a function to update the state grabbed with array distructuring

there is no special hook for sharing non visual logic, instead you can create custom hooks that are decoupled from ui

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

syntax parser

higher level code vs lower level - synonyms

A

a program that reads your code and decides what it does and if the grammar is valid. Your code is abstracted away and the program converts it to something your hardwar can physically understand = compilers and interpreters.

translate a program from scripting language to machine language

abstracted language
scripting language
vs
binary code
machine code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
5
Q

compiler vs interpreter, and which one is JS

A

A compiler takes entire program and converts it into object code which is typically stored in a file. The object code is also refereed as binary code and can be directly executed by the machine after linking. Examples of compiled programming languages are C and C++.

An Interpreter directly executes instructions written in a programming or scripting language without previously converting them to an object code or machine code. Examples of interpreted languages are Perl, Python and Matlab.

JavaScript is an interpreted language, not a compiled language. A program such as C++ or Java needs to be compiled before it is run. … More modern browsers use a technology known as Just-In-Time (JIT) compilation, which compiles JavaScript to executable bytecode just as it is about to run.

Just-in-time compilation is the conversion of non-native code, for example bytecode, into native code just before it is executed.

An interpreter executes a program. It may or may not have a jitter.

A JavaScript engine can be implemented as a standard interpreter, or just-in-time compiler that compiles JavaScript to bytecode in some form. The first JavaScript engines were almost only interpreters, but most modern engines employ just-in-time (JIT) compilation for upgraded performance.

Every browser provides a JavaScript engine that runs the JavaScript code. The Netscape browser used the SpiderMonkey JavaScript engine.

What is V8? V8 is Google’s open source high-performance JavaScript and WebAssembly engine, written in C++. It is used in Chrome and in Node.

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

lexical environment

A

Lexical Environment exists in languages in which it matters where the code is written.

When it comes to Lexical Environment, for example, of a function or a variable, we are really talking about where they will be located in the computer’s memory after compilation/creation. How they will interact with other functions, variables or elements of the program.

Simply “Where is it written and what surrounds it”.

function first() {
  var a = 10;
  var b = 100;
}
function second() {
  var c = 20;
  var d = 200;
  function third() {
    var e = 30;
 }
}
For example in the example above, the function first and second sit both lexically in the same place. Same goes for variable a and variable b. On the other hand in function second, variable c and d do not belong to the same lexical environment as variable e because it was created inside function third.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
7
Q

global object; global execution context

A

Execution context has 4 components:

  1. When you run your code in the creation phase first global object (window) is created inside the browser (chrome or firefox), as part of it’s execution context, which means that object is available to all the code running inside that window, inside that js file, inside that lexical environment,
  2. and there is s special variable that js engine created
    that sits inside that execution context, called this.

at the global level those 2 things are equal

when we say global in js it means not inside a function; in here, when var and f are lexically not sitting inside of function, they get attached to global object; you can do var a or window.a

  1. outer environment is the 3rd thing created, but for global execution context there is none.
  2. execution context is running your code
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
8
Q

Define object

Primitive vs object, list

A

comma seperated key value pair.

JavaScript defines 5 types of primitive data types:

string
number
boolean
null
undefined

In JavaScript, almost “everything” is an object.

Booleans can be objects (if defined with the new keyword)
Numbers can be objects (if defined with the new keyword)
Strings can be objects (if defined with the new keyword)
Dates are always objects
Maths are always objects
Regular expressions are always objects
Arrays are always objects
Functions are always objects
Objects are always objects
All JavaScript values, except primitives, are objects.

JavaScript provides a boolean primitive type that has two values of true and false.

The Boolean is also a wrapper object of the boolean primitive type. It means that when you use the Boolean constructor and pass in either true or false, you create a Boolean object.

To get the primitive value back, you call the valueOf() method of the Boolean object as follows:

However, if you call the toString() method of a Boolean object, you get a string value “true” or “false”.

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

Recursion

example with count down
example with factorial

base case
stack overflow
what is stack

A

What is Recursion?

The process in which a function calls itself directly or indirectly is called recursion and the corresponding function is called as recursive function. Using recursive algorithm, certain problems can be solved quite easily.

What is base condition in recursion?

In the recursive program, the solution to the base case is provided and the solution of the bigger problem is expressed in terms of smaller problems.

int fact(int n)
{
    if (n < = 1) // base case
        return 1;
    else    
        return n*fact(n-1);    
}

explains factorial: https://codeburst.io/learn-and-understand-recursion-in-javascript-b588218e87ea

In the above example, base case for n < = 1 is defined and larger value of number can be solved by converting to smaller one till base case is reached.

How a particular problem is solved using recursion?

The idea is to represent a problem in terms of one or more smaller problems, and add one or more base conditions that stop the recursion. For example, we compute factorial n if we know factorial of (n-1). The base case for factorial would be n = 0. We return 1 when n = 0.

Why Stack Overflow error occurs in recursion?

If the base case is not reached or not defined, then the stack overflow problem may arise.

when the computer or processor memory (often called stack), is filled more than its stack capacity. Then the stack overflow is leading to loss of elements in memory. You end up losing the foremost or recent element.

Let us take an example to understand this.

int fact(int n)
{
    // wrong base case (it may cause
    // stack overflow).
    if (n == 100) 
        return 1;
    else
        return n*fact(n-1);
}
If fact(10) is called, it will call fact(9), fact(8), fact(7) and so on but the number will never reach 100. So, the base case is not reached. If the memory is exhausted by these functions on the stack, it will cause a stack overflow error.
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
10
Q

recursive count down and factorial recursion examples

A

recursive count down

function countDownFrom(number) {
	if (number === 0) {
		return;
	}
console.log(number);    
countDownFrom(number - 1); }
countDownFrom(5);
// 5
// 4
// 3
// 2
// 1
function factorial(x) 
{ 
  if (x === 0)
 {
    return 1;
 }
  return x * factorial(x-1);

}
console.log(factorial(5));

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

Dimensions in react native

A

set orientation in state, onChange listener to get dimensions to update the state; apply conditional styling based on orientation

useWindowDimensions is the preferred API for React components. Unlike Dimensions, it updates as the window’s dimensions update. This works nicely with the React paradigm.

import { Dimensions } from ‘react-native’;

You can get the application window’s width and height using the following code:

const windowWidth = Dimensions.get('window').width;
const windowHeight = Dimensions.get('window').height;

Although dimensions are available immediately, they may change (e.g due to device rotation, foldable devices etc) so any rendering logic or styles that depend on these constants should try to call this function on every render, rather than caching the value (for example, using inline styles rather than setting a value in a StyleSheet).

If you are targeting foldable devices or devices which can change the screen size or app window size, you can use the event listener available in the Dimensions module as shown in the below example.

  • difference between window and screen only matters on android (should get window to get both)
  • window: reports width/height without the soft menu bar
  • screen: reports entire screen’s width/height

Example for functional component

import React, { useState, useEffect } from “react”;
import { View, StyleSheet, Text, Dimensions } from “react-native”;

const window = Dimensions.get("window");
const screen = Dimensions.get("screen");
const App = () => {
  const [dimensions, setDimensions] = useState({ window, screen });
  const onChange = ({ window, screen }) => {
    setDimensions({ window, screen });
  };

useEffect(() => {
Dimensions.addEventListener(“change”, onChange);
return () => {
Dimensions.removeEventListener(“change”, onChange);
};
});

return (

  {`Window Dimensions: height - ${dimensions.window.height}, width - ${dimensions.window.width}`}
  {`Screen Dimensions: height - ${dimensions.screen.height}, width - ${dimensions.screen.width}`}

);
}

const styles = StyleSheet.create({
  container: {
    flex: 1,
    justifyContent: "center",
    alignItems: "center"
  }
});

export default App;

dimensions are only calculated when the app starts, if it’s a portrait mode it’ll lock that in, and if you rotate it won’t change the width.

The component re-renders it’s content upon orientation change. You can, for example, pass landscapeStyles and portraitStyles to display these orientations differently. Works on iOS and Android.

you should set this with state
const [buttonWidth, setButtonWidth]=useState(Dimensions.get(window).width/4)
make an event listener change

but you have to use it in useEffect, otherwise outside of it you add a new event listener every time component rerenders. in useEffect you can clean it up before adding a new one every time component rerenders, so we always have one running event listener; this way it’s cleaner

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

event handler

A

Each available event has an event handler, which is a block of code (usually a JavaScript function that you as a programmer create) that runs when the event fires. When such a block of code is defined to run in response to an event, we say we are registering an event handler. Note: Event handlers are sometimes called event listeners — they are pretty much interchangeable for our purposes, although strictly speaking, they work together. The listener listens out for the event happening, and the handler is the code that is run in response to it happening.

button onClick={activateLasers}
Activate Lasers
/button

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

onChange vs change in react

A

onChange is inline synthetic react listener

custom event listener
Dimensions.addEventListener(“change”, onChange);

Neither approach is bad but, my recommendation is to use React’s onClick Synthetic Event because:

  1. It handles event pooling
  2. It handles removing event listeners for you
  3. It’s better optimized
  4. It’s more efficient on DOM resolution, and event delegation

This is not to say, never use custom event listeners. Use it only when you can’t do things with regular React events.

Event delegation: React doesn’t actually attach event handlers to the nodes themselves. When React starts up, it starts listening for all events at the top level using a single event listener. When a component is mounted or unmounted, the event handlers are simply added or removed from an internal mapping. When an event occurs, React knows how to dispatch it using this mapping. When there are no event handlers left in the mapping, React’s event handlers are simple no-ops.

SyntheticEvent is a cross-browser wrapper around the browser’s native event. It’s API is same as the browser’s native event, including stopPropagation() and preventDefault(), except the events work identically across all browsers.

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

where can you use hooks

A
  • can only use in root of your component, not in functions within component
  • can only be used in functional component or in hooks themselves
How well did you know this?
1
Not at all
2
3
4
5
Perfectly
15
Q

event delegation

A

Event delegation is a technique for listening to events where you delegate a parent element as the listener for all of the events that happen inside it.

I often use listening to all clicks in the document as an example, but it can be any element on the page.

For example, if you wanted to detect any time any field changed in value inside a specific form, you could do this:

var form = document.querySelector(‘#hogwarts-application’);

// Listen for changes to fields inside the form
form.addEventListener('input', function (event) {
	// Log the field that was changed
	console.log(event.target);

}, false);

To solve the problem mentioned in the above section, we will put together everything we have learned so far to make use of a technique called event delegation. In simple words, it leverages the bubbling effect to extract the handling logic of an event to a common ancestor of the elements where this event is triggered. In our previous sandbox, instead of adding listeners to the 150 li‘s, we would add only a single listener to the #palette element. This way, every time the user clicks on a color, the bubbling effect causes the event to propagate to the #palette element, triggering the execution of its listener. You can identify each color by using the e.target property, as we did in the original color palette sandbox.

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

the reason for event delegation

A

Modern applications heavily rely on events to provide interactive interfaces to users. It’s really common to have to handle events triggered on several elements in a web page. If you have, for example, a color palette component and you need to perform some action when the user clicks on a given color, you could just add a click handler to each individual color in the palette. This could be easily done during the initialization of the component. Let’s see a live example:

While the approach we’ve adopted is viable, it’s not as optimized as it could be. Our palette has 150 colors and, as a consequence, we are attaching 150 listeners to handle all of them. Besides, if our component had a feature that allowed the user to add custom colors, we would need to add our listener to each new color added to the palette.
Well, all of this look like a silly concerns, since computers are much faster nowadays. We don’t need to worry about optimizations so insignificant anymore, right? Wrong. The faster computers get, the more complex applications become as well. Every performance gain matters. Ok, but how to solve this problem? How to handle events for dozens, hundreds or even thousands of elements without adding individual handlers to each one of them?

17
Q

event bubbling

A

Event bubbling is the propagation of an event from its origin towards the root element. In other words, if an event occurs on a given element, it will be triggered on its parent as well and on its parent’s parent and all the way up, until the html element. If any of these elements has one or more registered listeners, they will be called. Therefore, the bubbling effect is only noticeable when at least one ancestor of the event’s origin has a listener for the same type of event. Otherwise, the propagation will happen silently, since there’s no listener to be called.
All of this is easy to see in the previous sandbox. When you click on the Sign in link, for example, not only its listener is executed, but the listeners of its ancestors as well. Besides, since the body (the white part) has no registered click handlers, nothing happens when you click directly on it.

https://javascript.info/bubbling-and-capturing

if you have 3 nested elements and all of them have alert on click, all of them will alert if you press on inner element in sequence,

18
Q

stop event bubbling

A

If you want to prevent bubbling from occurring, you can use the stopPropagation method:
document.querySelector(‘#signin’).addEventListener(‘click’, (e) => {
e.stopPropagation();
console.log(‘Sign in button click’);
});
In the above example, when the user clicks on the Sign in button, only its own listener(s) will be executed. Therefore, the click event won’t be propagated to its ancestors.

onclick=”event.stopPropagation(); for inline