Differences

This shows you the differences between two versions of the page.

Link to this comparison view

Both sides previous revision Previous revision
Next revision
Previous revision
javascript [2020/09/23 03:52]
paul [Objects]
javascript [2020/10/05 03:09] (current)
paul [Object Spread Operator]
Line 1: Line 1:
 ====== javascript ====== ====== javascript ======
 +
 +===== var, let and const ====
 +
 +A ''var'' is a statement that defaults a function-scoped or a globally-scoped
 +variable. It is also added as a non-configurable property to the global object.
 +
 +The ''let'' statement created a variable that is block scoped. They are still
 +accessible from blocks that are children of the block the variable was declared
 +in.
 +
 +If ''let'' is not written, javascript quietly creates a global binding and uses
 +it.
 +
 +===== Strings =====
 +
 +Javascript **template literals** allow you to add variables in a string.
 +
 +<code javascript>
 +let age = 33;
 +let name = 'Paul';
 +let out = `My name is ${name} and I am ${age}`;
 +</code>
 +
 +===== Object Literals =====
 +
 +<code javascript>
 +const person = {
 +  name: 'Paul'
 +};
 +
 +// You can add data willy nilly!
 +person.email = "[email protected]";
 +</code>
 +
 +==== Object Destructuring ====
 +
 +You can pull data out of an object using a technique called object
 +destructuring.
 +
 +<code javascript>
 +const person = {
 +    firstName: 'Paul',
 +    lastName: 'Sammut',
 +    age: 33,
 +    address: {
 +        street: '50 main st',
 +        city: 'NY',
 +        state: 'NY'
 +    }
 +}
 +
 +const { firstName, lastName, address:{ city } } = person;
 +</code>
 +
 +===== Arrays =====
 +
 +There are a bunch of array operations:
 +
 +''shift()'' - removes and returns the 0th' element of an array
 +''unshift()'' - adds 1 or more elements to the start of an array
 +
 +Iterating through arrays is a whole thing of course. There are a bunch of ways
 +to do it. You can while loop it, or you can make use of the ''for...of''
 +statement.
 +
 +==== Filter ====
 +
 +Arrays have a filter function that is very powerful. You pass in a function that
 +defines the filter criteria. Very cool.
 +
 +<code javascript>
 +let applicants = [ { name: "Joe Shmoe", country: "US", age: 33 },
 +                   { name: "Rob Parny", country: "GB", age: 29 },
 +                   { name: "Rob Parly", country: "GB", age: 16 },
 +                   { name: "Lem Meloo", country: "IT", age: 75 } ]
 +
 +let onlyUsApplicants = applicants.filter(app => app.country === "US");
 +</code>
 +
 +==== Map ====
 +
 +A ''map'' function allows you to go through the elements of an array and build a
 +new array with returned values of the function passed into map that can act on
 +each element.
 +
 +==== Reduce ====
 +
 +A ''reduce'' function is used to compute a single value from an input array. At
 +its basic form it requires a combining function that combines to elements of the
 +array.
 +
 +It can also be used to get a max or min of an array. For example:
 +
 +<code javascript>
 +let data = [  { name: "red",   count: 32 },
 +              { name: "green", count: 2  },
 +              { name: "black", count: 1  },
 +</code>
 +
 +==== Some && Every ====
 +
 +''some'' is a function that acts on arrays by taking in a logical test function.
 +If any of the elements in the array passes the test, it returns true.
 +
 +''every'' is a function that acts on arrays by taking in a logical test function.
 +If all of the elements in the array pas the test, it returns true.
 +
 +==== Composing ====
 +
 +''Composing'' is when you get start chaining high-order functions to get to a
 +result or subset of data in a few lines of code.
 +
 +<code javascript>
 +// Filter and map to a new array
 +let dirs = SCRIPTS.filter(script => script.living).map(script => { 
 +    return { name: script.name, direction: script.direction}; });
 +</code>
 +
 +===== Functions =====
 +
 +There's 3 ways of writing a function in JavaScript.
 +
 +Using a ''function'' expression:
 +
 +<code javascript>
 +const fun1 = function(x) {
 +  return x*x;
 +};
 +</code>
 +
 +Using a ''function'' decleration. The interesting thing with this is that you
 +can call a declared function before it's declated, as they are moved to the top
 +of their scope, and all code in that scope can use them. They also don't need a
 +semicolon at the end.
 +
 +<code javascript>
 +sayHello();
 +
 +function sayHello() {
 +  console.log("Hi!");
 +}
 +</code>
 +
 +Using the ''arrow'' notation. This is a third and compact way of writing
 +functions. If you don't put curly braces and have a single expression, it will
 +be returned.
 +
 +<code javascript>
 +const sayHi = () => { console.log('hi'); };
 +const returnOne = () => 1;
 +</code>
 +
 +Functions in javascript ignore extra parameters you pass in and also add
 +undefineds for parameters you don't pass in.
 +
 +Functions in javascript can be named or anonymous. They have access to local variables that are in the scope of their parent functions.
 +
 +<code javascript>
 +function fun2(){
 +  var output = ""
 +    if(typeof myGlobal != "undefined"){
 +      output += "myGlobal: " + myGlobal;
 +    }
 +  if(typeof oopsGlobal != "undefined"){
 +    output += " oopsGlobal: " + oopsGlobal;
 +  }
 +  console.log(output)
 +}
 +</code>
 +
 +===== Higher-Order Functions =====
 +
 +Higher-order functions are functions that operate on other functions, either by
 +passing them in as a parameter or by returning them.
 +
 +The shit you can do with functions is nuts.
 +
 +<code javascript>
 +let repeat = function(n, action){
 +  for(let i = 1; i <= n; i++){
 +    action(i);
 +  }
 +};
 +repeat(3, n => { console.log(n); });
 +</code>
 +
 +===== Callbacks =====
 +
 +You can pass around functions willnilly in javascript. You can easily pass them
 +in as parameters to functions.
 +
 +<code javascript>
 +function useFunction(func1, func2){
 +  func1("Pass this to func1");
 +  func2("Pass this to func2");
 +}
 +
 +var firstFunc = function(in){
 +  console.log(in);
 +}
 +
 +var secondFunc = function(in){
 +  console.log(in);
 +}
 +
 +useFunction(firstFunc, secondFunc);
 +
 +</code>
 +
 ===== Objects ===== ===== Objects =====
  
-These are defined with the following syntax:+Objecta can be defined as variables with member variables and functions insideĀ 
 +curly braces.
  
 <code javascript> <code javascript>
-var person = {+var myPerson = {
     firstName : "Jack",     firstName : "Jack",
     lastName : "Smith",     lastName : "Smith",
     age : 19,     age : 19,
     employed : true     employed : true
 +    fullName : function() {
 +      return this.firstName + " " + this.lastName;
 +    }
 +}
 +</code>
 +
 +They can also be defined as functions by making use the of the ''this'' and
 +''new'' keyword.
 +
 +<code javascript>
 +function Person(firstName, lastName){
 +  // construct the object using the arguments
 +  this.firstName = firstName;
 +  this.lastName = lastName;
 +
 +  // a method that returns the fullname
 +  this.fullName = function() {
 +    return this.firstName + " " + this.lastName;
 +  }
 +}
 +
 +var myPerson = Person("Paul", "Sammmut");
 +console.log(myPerson.fullName());
 +</code>
 +
 +===== HTML =====
 +
 +Javascript was designed to run in a browser and interact with HTML.
 +
 +You can embed javascript in html sources and make use of many function that can
 +modify HTML elements.
 +
 +===== Equality =====
 +
 +In javascript there are two equality statements, ''=='' and ''===''.
 +
 +Double equal: Loose equality check. Tries to coerse types so theres a match and
 +then compares content.
 +
 +Triple equal: Type and content have to match. Strict equality.
 +
 +===== Control Flow =====
 +
 +==== Switch ====
 +
 +Switch statements are wierd in that statements start executing at the
 +start of a matching label, and will keep executing accross other labels
 +until it hits a break.
 +
 +In the following if you pass ''sunny'' Dress Light and Go out will print.
 +
 +<code javascript>
 +switch(prompt("PUT IN WEATHER")){
 +  case 'rainy':
 +    console.log("Bring umbrella");
 +    break;
 +  case 'sunny':
 +    console.log("Dress light");
 +  case 'cloudy':
 +    console.log("Go out");
 +    break;
 +  default:
 +    console.log("Unknown weather type!");
 +    break;
 +}
 +</code>
 +===== OOP =====
 +
 +JavaScript OOP.
 +
 +==== Methods ====
 +
 +Methods in JS are simply properties that hold function values.
 +
 +<code javascript>
 +  let rabbit = {};
 +  rabbit.speak = function(line) {
 +        console.log(`I am saying '${line}'.`);
 +  }
 +
 +  rabbit.speak("hi!");
 +</code>
 +
 +==== Prototypes ====
 +
 +JavaScript has inheritance. Almost every object in javascript inherits (directly
 +or indirectly) from ''Object.prototype''. This gives every object some basic
 +properties, including methods, such as ''toString()''.
 +
 +==== Classes ====
 +
 +You can have classes in JavaScript but they can only contain methods. They
 +cannot contain non functions, such as variables.
 +
 +<code javascript>
 +class Rabbit{
 +  constructor(type){
 +    this.type = type;
 +  }
 +
 +  speak(line) {
 +    console.log(`This ${this.type} rabbit says '${line}'.`);
 +  }
 +}
 +
 +let killaRabbit = new Rabbit('killa');
 +let spottedRabbit = new Rabbit('spotted');
 +killaRabbit.speak('Hello precious..');
 +spottedRabbit.speak('I\'m spotted all ova');
 +</code>
 +
 +==== call function ====
 +
 +JavaScript has a call function that can be invoked on an function and allows you
 +to explicitly pass a ''this'' object as the first parameter.
 +
 +===== Object Spread Operator =====
 +
 +The Object Spread Operator is ''...'' and it allows you to spread concatenate lists in a one line. [[https://github.com/tc39/proposal-object-rest-spread|Link]]. 
 +
 +I was really confused about it when I saw it used to spread out properties of an object that was returned by a function [[https://vuex.vuejs.org/guide/state.html#object-spread-operator|here]].
 +
 +<code javascript>
 +computed: {
 +  localComputed () { /* ... */ },
 +  // mix this into the outer object with the object spread operator
 +  ...mapState({
 +    // ...
 +  })
 } }
 </code> </code>
  
  • javascript.1600833140.txt.gz
  • Last modified: 2020/09/23 03:52
  • by paul