Web Development

Declare variables user var a; Define it using a = 10;

var have function scope ref error outside, but can be passed down to children

Hoisting is moving the declaration to the top of the function (or global if not in function), but definition stays in place

Strict stops definitions without declarations

let and const have block scope const does not allow reassignment

Functions are classified as objects, can be passed anonymously by wrapping in brackets and calling ();

Closure saves the scoped variables of an outer function, so inner can be called - can be used multiple times to increment as it saves outer-scope

  const stringAdder = function() {
    let x = "";
    return function(s) {
      x = x + s
      return x;
    }
  }
 
  adder = stringAdder();
  adder("U")
  adder("of")
  adder("T")

Prototypes:

  Object.setPrototypeOf(child, parent)
  Student.prototype.sayLastName = function() {...}

this refers to the containing object of the call-site of a function

__proto__ the property of an object that points to the object’s prototype

Object.create(o) creates an object with o as the prototype

new creates a new instance, inheriting a prototype and filling the constructor

class same as what’s usually made, but not hoisted up like functions are - uses a constructor

Callback puts one function in another, and ensures that the second runs only runs after the first has

setTimeout is nonblocking that runs after x milliseconds

EventLoop is how JS is asynchronous - queueing things one after the other, to make sure not more than one thing at a time happens

new child.bind(parent) lets you bind an instance of a child to the scope of the parent onto new

Call and apply work the same way, except apply() needs an array

  child.call(parent, 'one', 'two')
  child.apply(parent, ['one', 'two'])

DOM Manipulation

  const newPost = document.createElement('div')
  newPost.className = 'post'
  const newPostContent = document.createTextNode("I am here.")
  newPost.appendChild(newPostContent)

Arrow functions

  const square = function(x) {
    return x * x
  }
  // - becomes -
  const square = x => x * x

Can have no arguments by using (), or multiple arguments as (x, y) Does not bind this, so be careful with usage

Functional Arrays

  // Filter
  const filteredStudents = students.filter((s) => {
    return s !== student 
  })
 
  // Map
  let bySeven = someArray.map(x => x * 7)
 
  // Reduce
  const toReduce = (accumulator, someJSON) => accumulator + someJSON.value
  someArray.reduce(toReduce)
  someArray.reduce(toReduce, 42)
 

React

  // onClick{...} call
  this.removeStudent.bind(this, student)
  // - equivalent to -
  () => this.removeStudent(student)
  constructor(props) {
    super(props)
    this.state = {...}
  }
 
  this.setState({...})
  componentDidMount()
  componentWillUnmount()

JSON

  JSON.parse(...)
  JSON.stringify(...)

Requests

  const someRequest = (objectID, callback) => {
    request({
      url: '...',
      json: true
    }, (error, response, body) => {
      if (error) {
        callback("Can't connect to server")
      } else if (response.statusCode === 200) {
        callback('Got resource')
      }
    }
  )}

Promises Equivalent to the request above, difference is it avoids callback hell which sometimes returns undefined.

  const somePromise = (objectID) => new Promise((reject, resolve) => {
    request({
      url: '...',
      json: true
    }, (error, response, body) => {
      if (error) {
        reject("Can't connect to server")
      } else if (response.statusCode === 200) {
        resolve('Got resource')
      }
    )}
  })

Express Is a series of middleware applications. You can have app.use to apply for all get, post, etc. you use afterward. You can also use next() if you have multiple app._ to send multiple responses.

  app.get('/someJSON', (req, res) => {
    res.send({...})
  })
 
  app.post('/someJSON', (req, res) => {
    let json = req.body
    someClass.save().then((result) => {
      res.send(result)  
    }, (error) => {
      res.status(400).send(error)
    })
  })

Middleware Compounding on the above, you can use middleware in app._, and you can use them as arrays

  app.get('/someJSON', [appOne, appTwo], (req, res) => {
    ...
  })

You can also create Mongoose Middleware, used the same way as above. You only want to allow next() if they’re authorized

  someSchema.pre('save', function(next) {
    const schema = this
    ...
    next()
  }

Security

Transport Layer Security (SSL): Client and Server use public-key encryption to agree on a shared persession secret, then use that secret to encrypt session data.

1) Injection: user puts something into the database. Prevent by validation or don’t trust raw input.

2) Auth and Sessions: exposed, unencrypted, expired, or any number of vulnerabilities. Can use oAuth instead.

3) Cross-site scripting: injecting a script onto the site, prevent by escaping.

4) Insecure Direct Object Reference: user accesses data by guessing routes, prevent by implementing authorization.

5) Security misconfiguration: Old patches, default passwords, unnecessary features, bad security settings, etc.

6) Sensitive Data Exposure: encrypt all sensitive data.

7) Missing Function Level Access Control: URL is too revealing, ensure that the user is authorized.

8) Cross-Site Request Forgery: different site has access to your POST, so they can pretend to be you - prevent by adding hidden token.

9) Using components with know security vulnerabilities: update everything and ensure you know what compenents are in your site.

10) Unvalidated Redirects and Forwards: apps use redirects or internal forwards where unvalidated parameters are used.


Extra

Conditional Operator condition ? exprIfTrue : exprIfFalse

AJAX Allows for dynamic web pages, meaning content in the page can get updated without a full page refresh

  fetch(url).then((res) =>
    ...
  )

Strict equality == doesn’t care about type, while === does