Open Carmer opened 7 years ago
I think the biggest point of value is to be consistent with good practices. Each of the readings generally have the same principles on them and that really drives home the point in writing clean code. Keep things readable. Keep things to the SRP. IN EJ specifically, I was really interested in the chapter on Objects - specifically when talking about this
and prototypes - since i had to use these in the exercisms. seeing that by using prototype affords us a few out of the box methods is extremely helpful.
Eloquent Javascript, Chapter 3 - Functions
Bread and butter of JS programming
Defining new vocabulary
Has parameters and body
Return statement explicitly
You can call a function before defining it
Ignores other arguments if given more than parameters define, if less than they define, the argument will come back as undefined
Closure = being able to wrap a specific instance of local variables in an enclosing function
Speed vs Elegance
Pure function is a specific kind of value producing function that not only has no side effects but also doesn't rely on side effects from other code.
Eloquent Javascript, Chapter 5 - Higher-Order Functions
Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level.
Higher order functions are functions that operate on other functions, either by taking them as arguments or returning them. They allow us to abstract over actions, not just values.
With apply method, you pass it an array of arguments, and it will call the function with those arguments.
Filter function helps you to build up a new array with only the elements passing the test, rather than deleting elements from the existing array.
Higher order functions really come in handy when you need to compose functions.
Bind method creates a new function that will call the original function but with some of the arguments already fixed.
Eloquent Javascript, Chapter 6 - Secret Life of Objects
Methods are simply properties that hold function values.
"this" points to object it was called on.
apply, bind, and call can be passed a specific "this" value.
Almost all objects have a prototype, which is another object used as a fallback source of properties.
An object created with new is said to be an instance of it's contructor
Constructors (and all functions) get a property called prototype which by default holds a plain, empty object that derives from Object.prototype.
Calling .toString on an array gives a similar effect to .join(",")
You can pass null to create an object with no prototype which is useful.
Eloquent Javascript, Chapter 17 - Objects & Inheritance
Several layers of OOP in Javascript: Layer 1 Object-orientation with single objects Layer 2 Prototype chains of objects Layer 3 Constructors as factories for instances Layer 4 Subclassing
Accessors are getters and setters
This chapter was a lot of information to get through and went into detail about the different OOP layers in Javascript. A lot of the information was a little hard to get through because I feel like I need to put some of these principles into practice. I feel like once I do so the ability to grasp some of the concepts will be easier but a lot is still unclear to me at this time.
Javascript Garden
Everything in Javascript acts like an object, with the only two exceptions being null and undefined.
Common misconception is that number literals cannot be used as objects.
Can also be used as hashmaps.
Properties of objects can be accessed in two ways: either by dot notation or by square bracket notation.
Only way to remove a property from an object is by the delete operator
Only widely used language that uses prototypical inheritance.
Lexical Scoping - all variables from blocks around a functions definitions are visible ~ those that are in the functions body that encloses it as well as those at the top level of the program.
In JS, functions are the only thing that can create a new scope. Free-standing blocks can be used but they do not allow for re-naming variables that have already been defined. These free-standing blocks are really only useful to group the body of an if statement or a loop.
JS doesn't care how many arguments are passed into a function, but if you pass too many, the extras get ignored, too few, and the missing parameters get re-assigned as undefined.
Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level, for example: using sum instead of a loop with a counter. This does however require the programmer to have some knowledge and experience with these abstractions in order to take advantage of them.
Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher order functions. Higher order functions allow programmers to abstract over actions, as well as values. You can have functions that create new functions, change other functions, and provide types of flow control.
Prototypes are another object that is used as a fallback source of properties. When an object gets a request for a property that it does not explicitly have, its prototype will be searched for that property, then the prototypes prototype, and so on. (ex: Object.prototype, Function.prototype, Array.prototype)
Getter / Setter methods allow us to specify a function to be run when a certain property is read or written; often the purpose is to restrict certain properties to certain limits or parameters. These can also be added to existing objects.
Some very useful concepts of objects
I thought this was a great overview from chapter 1: "Roughly, all objects in JavaScript are maps (dictionaries) from strings to values. A (key, value) entry in an object is called a property. The key of a property is always a text string. The value of a property can be any JavaScript value, including a function. Methods are properties whose values are functions."
proto ( proto ) is a special property for getting and setting the prototype of an object, granting direct access to [[Prototype]].
There are three levels of protecting an object, listed from weakest to strongest they are: Preventing extensions, Sealing, and Freezing.
To determine object properties, iterate over property keys and use a for - in loop with hasOwnProperty().
Constructors are similar to Classes in other languages, and are used to create objects of similar type and property.
Privileged methods - functions created in the constructor added as instance methods. Meaning that, on one hand, they can access private data; on the other hand, they are public and therefore seen by prototype methods. They serve as mediators between private data and the public (including prototype methods).
I found this to be an awesome little cliff notes version of the other readings. With a ton of code snippets and concise explanations, I have a feeling I will be referring to this alot more than the other readings, especially for things like quick syntax confirmation.
I also like how it went over Array iteration, array properties, and the array constructor, as well as numerous other core JS properties, in a nice reference format.
Chapter 3 (Eloquent): Functions
Chapter 5 (Eloquent): Higher Order Functions
Chapter 6: (Eloquent) The Secret Life of Objects
Chapter 17: Objects and Inheritance (Speaking JavaScript)
JavaScript Garden
Chapter 3 (Eloquent): Functions This chapter was extremely valuable to me. It wasn't until I understood the power and structure of functions that JavaScript actually began to click in my mind. Learning that I could save functions to variables and call those variables similarly to Ruby methods was awesome. Weird nuances with functions that I learned is the fact that functions must have () to take arguments, even if the function doesn't take any arguments. Also, the fact that functions MUST SPECIFICALLY return a value is pretty interesting. I caught myself often forgetting to "return" things while working through those exercises. The nice thing about JavaScript functions, they are a lot more easy-going than other languages, such as C#, which makes you declare the type of value the function is returning. That's great.
Chapter 5 (Eloquent): Higher Order Functions Right off the bat, this chapter really spoke to me, saying that complexity is the death of an efficient program. I think I have a tendency to write uglier and more complex programs when working with lower level languages. For some reason, the curly braces and semicolons make it naturally look ugly and make me think I have a pass on writing clean, clear code. This chapter proved why my tendencies are not correct. This chapter easily has some of the coolest things I've learned so far about JavaScript. Learning about using and creating higher-order functions and using functions as arguments for other functions is amazing. These concepts hit very close to what I learned while working through Lololodash. It was extremely confusing to see functions within the parameters at first, but after realizing the order of operations, it became clear how powerful higher-order functions can be when writing complex problems. It is important, however, to remember to keep things as simple as possible and not create complex functions for complex-sake. Complexity can make code difficult for others to work on and may hurt efficiency and run-time.
Chapter 6: (Eloquent) The Secret Life of Objects This chapter was a great read. I feel like one of the most difficult things to learn about JavaScript after learning Ruby is JS Objects. While we relate them to hashes, they are not exactly the same as the hashes we know and love. I noticed this while comparing my exercisms work with others. More advanced coders could use and manipulate JS objects to do a whole lot more than just store and recall values. This chapter showed several awesome concepts including using object keys to refer to functions. This use looks a lot like class methods... but under the hood, it's working completely different than Ruby. I still need to do a lot more research and messing around to fully grasp the concept of prototypes. Reading about it felt similar to when Jeff initially showed us the abstract depth of Ruby classes and prime classes. While in theory it makes a bit of sense, I am not fully understanding what is happening in the background. It's interesting, actually, considering that while working through Exercisms, I was manipulating the prototype and didn't even realize it. Overall, this chapter showed me just how much was happening in the background... and how important it is to understand the ins and outs of objects to write truly magnificent and efficient programs. I am definitely going to re-read this chapter.
Chapter 17: Objects and Inheritance (Speaking JavaScript) Diving deeper into the JavaScript pool... The depth and power of JS objects continues to baffle me. While I feel like I was holding on to what was happening in this chapter, it was easy to get tripped up and confused. The more I learn about dot operators and how objects can hold functions, the more I realize how you can manipulate JavaScript to do similar things as Ruby. At the same time, however, objects can be as simple as hashes, using functions such as keys, you can navigate the object in the same way a Ruby hash can be navigated. This chapter was very dense, with a lot of interesting information, but, to be honest, the whole time I was reading I just felt like I needed to apply the knowledge to fully understand it and learn it. It's definitely beneficial to at least be exposed to the concepts, and I will be saving a link to this chapter for future reference.
JavaScript Garden Another great resource for future reference. I really think this reading should have been the first thing we did for prework before jumping into the NodeSchool. It's a clear and well-written piece of all the weird nuances JavaScript has. There is little to no assumed back knowledge, and knowing what we know about Ruby and other programming languages, I thought it did a good job pointing out the major differences and how to avoid falling into the pitfalls. I honestly learned a whole lot more reading through this documentation and am excited to apply my new skills. The way JS Garden described prototypes really helped my understanding. I am learning the differences between Ruby and JS and inheritance. While Ruby directly inherits, JS uses prototypes to emulate the inheritance feeling. Learning how to chain prototypes together makes a lot of sense, and I really feel that concept starting to click. Learning more about function declarations was very helpful. I have been going back and forth with whether I should declare a function similar to Ruby or declare a variable which equals a function. I am still struggling to understand the full scope of 'this' and how it is different than 'self' in Ruby. I think the idea of the global scope is throwing me off. Arrays in JavaScript are real interesting. I don't know what it is, but I'm really kind of liking the lack of enumerables and the custom ways you can work your way through arrays. Overall, this was a great read, and I can't wait to refer back to it as I'm writing some awesome JavaScript programs.
chap 3 - functions
I appreciated the clarification on how js handles scoping, especially that each function creates its own scope. I like the let {}
block, as the ability to define mine own scope when needed is useful. I also didn't realize the difference between var foo = function()...
and function foo() = ...
. I'm not sure how the function syntax moves the function to the top when javascript is interpreted. As I've been learning Elixir and functional programming over the break, it is nice that javascript has closures and first class functions. The very loose attitude about arrity of functions is frustrating however. I'm also reluctant to use closures in a language where the variables passed into the closure can be changed outside the closure (boo mutability!)
chap 5 - higher order functions I think it is very useful to see that patterns we are used to as enumerables in Ruby are relatively straight-forward to build. They are similar to an explicit for-loop, but designed with a general purpose (i.e. map applies a function to an array). I feel like I got more out of this because I had recently built these functions (map, reduce, etc.) with recursion in a functional programming language. As many problems as I have with javascript, the ability to easily pass functions (named and anonymous) as arguments is very useful
chap 6 - the secret life of objects
The most useful thing about this article was learning about prototypes and the javascript inheritance model. Prototypes seem very similar to inheritance, the Object object
in Ruby (and the idea of eigenclasses), but they are used in ways similar to a class definition. Constructors seem to be how javascript handles the idea of class, particular given the instanceOf
syntax. The ideas of polymorphism and encapsulation seem the same as Ruby.
chap 17 - objects and inheritance
There is a lot going on in this reading. While a lot of the material has been covered in the previous chapters, this describes the same ideas in a much denser way. It was nice to get explicit confirmation of my understanding of constructors as analogous to classes. The biggest take away for me wasn't a particular thing I learned but that (essentially) everything I already know has equivalents in javascript, even if they are much uglier. Also, spending time with a pure functional language over break (Elixir) I find it quite frustrating that even Object.freeze(obj)
leaves values somewhat mutable.
javascript garden -
This is awesome! A website that explicit acknowledges the weirdness of javascript and gives a frank discussion of workarounds and common frustrations. I really appreciated the clarification that prototype is a different model of inheritance. Prototyping felt similar to inheritance but I wasn't sure what was different about it. It was also super helpful that they explicitly layout 5 different cases for the meaning of this
, which helped clear up my confusion regarding this. I also really appreciated the discussion of automatically inserting semicolons. I had heard 'javascript doesn't require semicolons' said somewhat jokingly, and now I understand
Chapter # 3 - Functions
Chapter # 5 - Higher-Order Functions
Chapter # 6 - The Secret Life of Objects
Chapter # 17 - objects and inheritance
It seemed to me that this chapter was added to our read in order to further our knowledge in functions, objects, constructors, and so on. The biggest take away here is that I can pretty much apply all the knowledge learned in Ruby in JavaScript, the key is understanding how similar approaches are applied differently in JS.
JavaScript Garden
It is necessary to understand the prototypal inheritance model before being able to write complex code that makes use of it. Also, it is very important to be aware of the length of the prototype chains in the code and break them up when necessary to avoid possible slow down and performance issues. The hasOwnProperty is the most reliable method to check whether a property exists within an object or not. It's often recommended that hasOwnProperty is used in many cases when iterating over object properties. Although omitting the new keyword may result in some bugs, it's certainly not ideal to drop the use of prototypes altogether. In the end, we should be able to understand which solution is better suited for the needs of our application. In short, The JS Garden is an amazing resource that should be saved for future reference and understanding.
let
keyword creates a variable scoped to its container block, as opposed to var
, which is scoped to its container function.undefined
.reduce();
, map();
, filter();
, forEach();
new
keyword in front of it causes it to be treated as a constructor. An object created with new
is an instance of its constructor.own
property of an object is stored directly in that object whereas an inherited property is stored in one of its prototypes.value, writeable, get, set, enumerable, and configurable
.delete
operator.null
and undefined
.Array
constructor because they are shorter, have a clearer syntax, and increase code readability.strict equality
operator.instanceOf
operator should only be used when dealing with custom made objects that originate from the same JS context.Typeof
. In order to check the type of an object, it is recommended to use Object.prototype.toString
.eval
should never be used. setTimeout
and setInterval
can do the same thing without the security risks.setTimeout
or setInterval
.Eloquent JavaScript Ch.3
Using var makes an entirely new variable local to that function (unless it is global) while simply calling the variable name can allow you to reassign a new value to that previously declared variable. This allows you to reuse variable names.
Functions are the only thing which create new scopes. Functions can be passed as arguments. Variables that hold functions are just regular variables that can have their values reassigned.
Function declarations are an alternative to assigning the function to a variable. Function declarations aren't part of the regular top to bottom flow control in JS. You should only use function declarations in the outermost block.
Functions can take optional arguments which seem to be like default arguments in Ruby.
Closure allows you to reference a specific instance of a local variable inside an enclosing function.
Eloquent JavaScript Ch.5
forEach is useful in place of manually iterating with a for loop.
Functions can change other functions and define new types of control flow.
You can pass arrays of arguments to functions using the apply method.
You can pass a function as an argument of another function.
The filter function creates a new array with only the items which fit the filter's requirements, and the filter itself is just implemented by building your own custom function.
Binding creates a new function which fixes arguments when calling an already established function.
Eloquent JavaScript Ch.6
This chapter was very dense, and I will definitely need to re-read it. I'm still unclear about the nature of prototypes, although I'm inclined to analogize it to inheritance in Ruby (really not sure about that, though).
Object.create allows you to create an object with a specific prototype.
Using constructors allows you to create objects that derive from a shared prototype. You create this new instance using "new."
Every instance of a constructor has an empty object which comes from Object.prototype, and this quality allows you to add methods to the constructor which can then be called upon instances of the constructor.
Getters and setters allow you to include properties that are not methods (I think this is sort of like the attributes of an object in Ruby but am unsure). This will just run a function when a property is read (get) or written (set).
Defining a new vocabulary word to wrap a piece of a program in. Purpose is to reduce repetition and structure programs. Purpose is to reduce repetition and structure programs.
Definition
var addOne = function(x) {
return x + 1;
};
console.log(addOne(2));
=> 3
function
Scoping
Possible to change global vars inside function.
var x = 'one'
var f1 = function() {
var x = 'two'
}
f1();
// console.log(x) => 1
var f2 = function() {
x = 'two'
}
f2();
// console.log(x) => 2
Scopes can be nested
Functions can be values
Shorter Declaration
function addOne(x) {
return x + 1;
}
Function Declaration can be below the code that uses it
Arguments
Recursive
A useful principle is not to add cleverness unless you are absolutely sure you’re going to need it. It can be tempting to write general “frameworks” for every little bit of functionality you come across. Resist that urge. You won’t get any real work done, and you’ll end up writing a lot of code that no one will ever use.
Eloquent Javascript Chapter 3: Functions
1) In other programming languages, a block of code between the braces produces a new local environment. But in Javascript, functions are the only things that create a new scope.
2) Function variables usually simply act as names for a specific piece of the program.
3) Optional Arguments: JavaScript is extremely broad-minded about the number of arguments you pass to a function. If passed too many, the extra ones are ignored. If passed too few, the missing ones will become 'undefined'. In this case, we can set the optional argument to a default value if it is not passed in.
4) A good mental model is to think of the function keyword as 'freezing' the code in its body and wrapping it into a package (the function value).
5) Assuming number is an integer: var numberString = String(number); will convert it to a string, like to_s in Ruby.
6) I thought declaring functions in the following two ways was equivalent:
var f = function(a) {
console.log(a + 2);
};
function g(a, b) {
return a * b * 3.5;
}
But apparently the former creates a function value f, hence the semicolon at the end. And the latter declares g to be a function.
Chapter 5: Higher-Order Functions
1) Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher order functions. For example, you can have functions that create new functions, functions that change other functions, functions that provide new types of control flow.
2) JSON.stringify() - takes a JavaScript value and returns JSON-encoded string. JSON.parse() - vice versa.
3) The function is 'pure', if it does not modify/mutate the data(e.g.,array) it is given.
4) Some built-in methods for arrays in JavaScript: forEach, filter, map, reduce, every, some (need more exercises on these).
5) Although it is possible to write elegant code through abstractions, abstractions add layers between input and output which causes the computer to do more work.
6) Apply: functions have an 'apply' method that can be used to call them with an array specifying their arguments.
7) Binding: the bind method, which all functions have, creates a new function that will call the original function but with some of the arguments already fixed.
Chapter 6: The Secret Life of Objects
1) Methods are simply properties that hold function values.
2) 'this': object.method() { this }, 'this' is the object itself, like self.
3) Prototype: In addition to their set of properties, almost all objects also have a prototype. A prototype is another object that is used as a fallback source of properties. When an object gets a request for a for a property that it does not have, its prototype will be searched for the property, the the prototype's prototype, and so on. Object.prototype is the entity behind almost all objects, their great ancestral prototype.
4) Constructors: a more common way to create objects that derive from some shared prototype. In JavaScript, calling a function with the 'new' keyword in front of causes it to be treated as a constructor, so the object created with 'new' is an instance of the constructor. It is a convention to capitalize the names of constructors.
5) Enumberable vs. nonenumerable properties: all properties that we create by simply assigning to them are enumerable. The standard properties in Object.prototype are all nonenumerable and therefore do not show up in for/in loop, for instance.
6) Polymorphism: when a piece of code is written to work with objects that have a certain interface, any kind of object that happens to support this interface can be plugged into the code, and it will just work. Polymorphic code can work with values of different shapes, as long as they support the interface it expects.
7) Using a variable name starting with an '_' or consisting entirely entirely of a single underscore is a way to to indicate that this argument is not going to be used.
Speaking JavaScript Chapter 3: The Nature of JavaScript JavaScript is:
Chapter 17: Objects and Inheritance
Layers of OOP in JS:
Subclassing - creating new constuctors by inheriting from existing ones.
Layer 1: Single Objects
Three kinds of properties:
Object Literals
var jane = {
name: 'Jane',
describe: function () {
return 'Person named '+this.name;
},
};
Based on the above example:
Delete only affects direct, noninherited properties, without touching the prototypes.
Bracket operator coerces its interior to string:
var obj = { '6': 'bar' };
> obj[3+3] // key: the string '6'
'bar'
An empty object literal is almost always a better choice than the constructor:
var obj = new Object(); // avoid
var obj = {}; // prefer
Layer 2: The Prototype Relationship Between Objects
The following code creates objects jane and tarzan that share the prototype PersonProto:
var PersonProto = {
describe: function () {
return 'Person named '+this.name;
}
};
var jane = {
name: 'Jane'
};
var tarzan = {
name: 'Tarzan'
};
Layer 3: Constructors - Factories for Instances
Layer 4: Inheritance Between Constructors
function(future) {code}
is a function declaration; it does not follow top-to-bottom flow of control
for (i=0, i<3, i++)
, a potentially better way is similar to Ruby's each: products.forEach(function(product, index)) {code would go here});
map
is destructive, forEach is not. map
filter
builds a new array with some elements filtered outreduce
combines all elements of an array into a single valueaddToThis.call(objectCalled, argumentOfFunction)
addToThis.apply(obj, arrayOfArguments)
var blackRabbit = new Rabbit("black");
var map = Object.create(null);
new
obj.constructor.name
func.call(jane, 'Tarzan');```
- you need to call jane again or else it won't know how to pull sayHelloTo for func
We can't get away from Javascript. It's everywhere. You can declare a function by var <name>(){};
or function <name>(){}
. Has similar scope as Ruby. Can accept any number of arguments. If there are more arguments they are simply ignored, if there are too few the remaining are "undefined." We can nest functions within each other. In this case the main function will "freeze" and get the return function(...){...}
will then get its necessary info to execute and then the rest of the function will continue. JS loves SRP as much as Ruby. For arrays we still have access to functions like reduce, map, forEach, for, etc. this
is analogous to self
in Ruby. new <constructorName>
== Class.new
in Ruby.
.this
refers to the object it was called on.Object.create(null)
creates a fresh new object with no properties.delete obj.stuff
.prototype
is an example of an internal property of an object.someKey in obj
returns true if the object has someKeyfor(var key in obj)
to iterate over object keys.Object.property
Object.method()
Object.property = value
will create if doesn't existdelete Object.property
object['property']
apply()
doesn't know what object methods were called on so they need to be repeated ex: thing.apply(thing, ['stuff'])
Object.getOwnPropertyNames(obj)
returns the keys of all own properties of obj
Object.keys(obj)
returns the keys of all enumerable own properties of obj
value
writable
get
set
enumerable
configurable
new
operator is usedvar thing = function(){};
function thing(){}
return
statements ejects from the current functionreturn
is required to return a value from a functionlet
to allow scoping inside blocksundefined
valuesconsole.log()
forEach
instead of for
when iterating over an array
method.forEach(array, function(){...})
apply
passes an array as a parameterfilter
builds a new array (from an existing array) based on passing criteriamap
builds a new array (from an existing array) from an applied function's return valuesreduce
operates the same as it does in ruby, reducing an array into a single valuesbind
method
this
set to a valuethis
refers to the object which called the methodcall
operates like bind
or apply
and can be passed a this
valuenew
creates a constructor from a function
new thing()
this
variable bound to the fresh objectObject.prototype
Object.defineProperty()
allows for the control of the property typenull
when using .create
instanceof()
returns true/false -- can be used to show inheritanceChapter 3. The Nature of JavaScript
JS it object oriented
JS is dynamically typed -- variables and objects can hold properties of any type
It "fails silently" -- exception handling is an afterthought in JS
It exists as part of the web platform
JS inherits and was influenced by several programming languages
Chapter 3 (Eloquent): Functions
A function defines new vocabulary for a program
A function is an instruction that can used throughout the program or scoped to a specific part of the program
You can nest the scope of a function within other functions
Those functions can contain variables that are scoped with the specific function or globally
Functions may also act as variables and store values
A function may take optional arguments and will not throw an exception if it takes too many arguments
A functions variables are recreated each time that function is called, allowing us to use the same data throughout the program
Chapter 5 (Eloquent): Higher Order Functions
Name variables for their responsibility in the program
Higher order functions allow the user to write functions that create functions
Similar to ruby, the map method will transform the data set
Reduce again allows us to compute a single value from a data set
Nesting loops leads to inefficiency, loop n within m leads to a total run time of 'm' times 'n'
Reduce and concat act as flatten in JS
Efficiency over readability?
Chapter 6: (Eloquent) The Secret Life of Objects
Methods are properties that hold function values
A prototype is an object that is used as a fallback source for properties
And object created with /new/ is an instance of its constructor
Constructors carry the object prototype
Prototype properties can interfere with explicit properties in some cases
.toString is an example of polymorphism
JS uses getters and setter to read and write specific properties
Chapter 17: Objects and Inheritance (Speaking JavaScript)
JS has kinds of properties: properties, accessors, internal properties
Dot (.) operator provides syntax for getting properties
Assignment (=) operator provides syntax for setting properties
delete lets you remove a property
configurable true/false determines if a property can be deleted or edited
In strict mode, this is always undefined
You cannot delete/change inherited properties from the objects that inherited them
A prefixed underscore can make data private
Super call?
Properties can be accessed through the dot notation or square bracket notation
'This' exists in the global scope and 'this' inside of test.foo refers to test not 'foo'
The only closure in JS is a function closure
There is a difference between global and current scopes when defining and using variables
Local variables only exist within function parameters
Var and function declarations will be moved to the top of their enclosed scopes
The use of global variables is considered bad practice
A for in loop caches the value of the array with array.length
Use [] to create arrays not 'new Array'
Weak typing in JS coerces types to compare them
=== is the strict equality operator and will not coerce data types
eval only executes in the local scope
null and undefined are not the same expressions of 'nothing'
JS parser will automatically insert semicolons to end expressions but 'guesses' where they should go -- never omit semicolons
Chapter 3 (Eloquent): Functions JavaScript scopes variables depending on where they are created Prototypes are used to add methods and properties to objects Functions can be stored as values Being able to reference a specific instance of local variables in an enclosing function is called closure. Functions can be roughly divided into those that are called for their side effects and those that are called for their return value
Chapter 5 (Eloquent): Higher Order Functions Abstractions hide details and give us the ability to talk about problems at a higher (or more abstract) level. Functions that operate on other functions, either by taking them as arguments or by returning them, are called higher-order functions. The map method transforms an array by applying a function to all of its elements and building a new array from the returned values. Higher-order functions start to shine when you need to compose functions.
Chapter 6: (Eloquent) The Secret Life of Objects Methods are simply properties that hold function values. A prototype is another object that is used as a fallback source of properties. A more convenient way to create objects that derive from some shared prototype is to use a constructor. A prototype can be used at any time to add new properties and methods to all objects based on it. When a piece of code is written to work with objects that have a certain interface—in this case, a toString method—any kind of object that happens to support this interface can be plugged into the code, and it will just work. This technique is called polymorphism—though no actual shape-shifting is involved. Polymorphic code can work with values of different shapes, as long as they support the interface it expects.
Chapter 17: Objects and Inheritance (Speaking JavaScript) The value of a property can be any JavaScript value, including a function. Methods are properties whose values are functions. JavaScript’s object literals allow you to directly create plain objects (direct instances of Object)
* Some quirks unique to javascript are: it has no integers, only floats. It has no built-in modules.
* Javascript is a dynamic, dynamically typed, functional and object-oriented programming language which fails silently and is an essential part of the web platform
* Functions are like the words in your vocabulary, they allow you to do work.
* Variables defined inside of functions are only accessible with that function
* Variables initially declared outside of a function have a global scope
* Functions can be created inside of other functions. These functions each have their own individual variable scope and access to the variables of the ‘parent’ functions which wrap them
* Control flow - the order the machine executes the code
* With ‘function declaration’ short hand you can define functions which are moved to the top of the control flow and thus can be called above where they are declared
* Call Stack - The order of the control flow and where in the code the computer should jump to next, the call stack takes memory which can be overloaded in which case you will get an error
* You can create functions with variable numbers of arguments, if you pass to many arguments to a function the get ignored, if you pass to few the unassigned arguments get set equal to ‘undefined’
* Pure function - given the same attributes will always produce the same results
* Higher order functions - functions that operate on other functions either by taking them as arguments or by returning them
* Javascript has a map methods map(array, transformMethod(()) which returns an array with every element transformed
* It also has a reduce function which computes a single value from an array
* Nested loops can be a source of series slow down in your program
* ‘bind’ method - creates a new function that will call the original function but with some the arguments already fixed
* Objects act as a simple interface for programmers to interact with
* prototype: another object that is used as a fallback source of properties. You can create an object with a specific photo type which can contain function and state ubiquitous to all objects with that prototype.
* If you add a property to an object who's prototype has the same name the objects property will store the value but the prototype will remain unchanged. Prototype property values could show up when enumerating through an object, to avoid that we should define our properties as ‘non-enumerable’
* Sometime prototypes get in the way, you can create objects without prototypes
* Constructors: Use new keyword to create a new object / ‘instance’ of its constructor. Constructors are capitalized to distinguish them.
* polymorphism - methods with same names in different classes doing similar things
* you can use the ‘get’ and ‘set’ key words to specify a function to be run when the associated property is read or written
* you can use inheritance to allow one function to access the functions of another class
* object literals - plain direct instances of object (with state and behavior)
* .nameOfVar - . operator for reading properties
* numbers can be used as property values but they will be interpreted as strings
* You sometimes have to convert a value into an object
* ‘this’ is always a parameter that comes with a method, it represents the object on which the method has been called. its value is ‘undefined’
* you can protect objects in three ways (preventing extensions: making it impossible to add properties to an object, sealing: making all the properties unchangeable, freezing: makes all properties permanently read only
* You can have constructors inherit one another prototype properties as well
* There are not that many generic methods in Javascript, most are around arrays and strings
* Everything but null and undefined acts like an object in javascript
* hasOwnProperty is the only reliable method to check for the existence of a property on an object
* loops can iterate over the prototype chain what iterating over the properties of an object, therefore you have to filter out unwanted properties side the loop body
* closures: functions insides of other functions have access to the scope of the ‘parent’ functions which wrap them.
* every function in javascript has a special variable called ‘arguments’ which is an object with a list of all arguments passed to that function, you can convert this object into an array
Speaking JS: Chapter 3
Eloquent JS Ch. 3: Functions
let
block, in which you could define your own scopeChapter 5 (Eloquent): Higher Order Functions
forEach
does something on each element, filter
builds a new array with some elements filtered out, map
builds a new array in which each element has been through a function, and reduce
combines all elements into one value.apply
and bind
methods. apply
can be used to call them with an array specifying their arguments, while bind
is used to create a partially applied version of the function. I still think I need to do some practice on these ones!Chapter 6 (Eloquent): The Secret Life of Objects
Object.prototype
, Function.prototype
, and Array.prototype
are all different prototypes get
or set
words - these are for properties and allow you to specify a function to be run Chapter 17(Speaking): Objects and Inheritance
delete
operator lets you completely remove a property from an object (both the key and the value pair)Javascript Garden
Chapter 3 (Speaking)
Chapter 3 (Eloquent)
let
vs var
seems as though it may help a little with the confusion.if
blocks or loops!Chapter 5 (Eloquent)
forEach
to clean up an iterating function is something I’ll refer back to. .apply
to pass along multiple arguments within one argument - very cleverfilter
, map
, reduce
methods on arrays - lots of similarity to RubyChapter 6 (Eloquent)
this
to point to an objectObject.prototype
- so much like Ruby! Array and function prototypes as well.new
in front of it makes it a constructornew
makes it an instance of its constructorget
and set
properties!instanceOf
returns a boolean, checks for constructorChapter 17 (Speaking)
[[Prototype]]
)=
to set value of a property - creates property if it doesn’t exist, delete
removes property.keys
accesses keys, values can then be called with bracket operatorslice
converts args into an arraythat = this
- another strange JS workaround - I prefer the forEach
example. preventExtensions(obj)
, seal(obj)
, freeze(obj)
to make objects less or nonwritable. Protects properties but not values.JavaScript Garden will probably be the most helpful of all of these - it clarifies a lot of the things I didn't understand in the chapters. This will be a really helpful reference.
Chapter 3(Speaking): Quirks: No int, arrays are not technically indexed, but map btwn # & element Elegances: First class functions, closures, prototypes, object literals, array literals
Chapter 3(Eloquent): Lexical Scoping: Sometimes referred to as Static Scoping. Access to variable in outer scope/function and own function. Let vs Var: Let creates a variable local to the block not the function Arguments: Won't throw an error, ignore too many, set as undefined for too few Closures: ... ?? Being able to reference a specific instance of local variables in an enclosing function ... ?? Looping vs Recursion: Looping is faster but recursion is more elegant, Worry about readability first though.
Chapter 5(Eloquent): Higher-Order Functions: Pass functions into other functions. Var declared inside inner isn't available in out function here. forEach, map, filter, reduce: All available, similar to Ruby enumerables. Looping is faster but less readable than these. forEach, map, and filter can take a second argument for index. apply: within body of a function, will apply function for each arg not just first bind: available on all functions, partially applied version of the function
Chapter 6(Eloquent):
Objects!!
Prototypes: another object that is used as a fallback source of properties. Look-up chain, inherits from parent generations properties
Constructors: new => constructor, provides this = newObj, creates instances, the prototype of a constructor is Function.prototype no Object.prototype. A constructor's prototype property is the instances of the constructor, not is's prototype(Function.prototype). Can overwrite a property locally.
Array.prototype.toString !== Object.prototype.toString
Properties we create are enumerable, but can set that to false with .defineProperty.
hasOwnProperty checks if property is of the object not its prototype
Polymorphism: code that works w/ different types of values i.e. toString
instanceof: checks inheritance line
Chapter 17(Speaking): Methods vs Properties: properties are key:value methods are key: fuction delete obj.hello: returns t/f use sparingly use obj = {} vs obj = new Object Strict Mode and Callbacks: I'll need to learn more about this. .call: jane.prototype.call(jane, 'Tarzan') .apply: call w/ array of arguments .bind: sends along params to new function .construct: .bind.apply() for-in: avoid when iterating over own code protecting obj: .preventExtensions, .seal, .freeze
Garden: This is a good review of everything that has been covered.
Chapter 3. Speaking - The Nature of JavaScript • It's dynamic- can easily be changed and manipulated • It is both functional and object-oriented • It's error messages can be ambiguous, if they are event present • It is compiled by javascript engines after the source code is deployed • Though typically used directly in browser, it can be used without (ex: node.js) • It's creation takes influence from java, perl, awk, hypertalk, scheme, and self
Chapter 3. Eloquent JavaScript - Functions • Functions are just variables set to equal the function itself • Functions can take many parameters or no parameters • Functions can be created inside of functions, where, those results remain local to the nested function • Declaration notation can be used (rather than defining a function as a variable); when this is done, the function does not have to be at the top of the page/declared before it is used. Declaration notation should not be used with nested functions. • You can pass as many arguments as you want in JS, but if you pass too many, the extras will just be ignored.
Chapter 5. Eloquent JavaScript - Higher Order Functions • More lines doesn't mean a better program • Using abstractions can make code simpler and easier to understand as the program grows and changes hands • Higher order functions are just functions that create, change, or return other functions • The JSON format is a commonly used format for communicating and storing data but you can't use variables or functions within. • Filter, forEach, map, reduce, are standard methods for arrays • We can compose functions for greater clarity and abstraction • Using these built-in methods can significantly slow down programs however so we have to weigh the cost of abstraction against the cost of performance
Chapter 6. Eloquent JavaScript - The Secret Life of Objects
• Prototypes sound a lot like Ruby classes to me, based on the description in this chapter
• Constructors seem similar to initializing a object via a class in ruby by using new
• Object properties can be overridden for specific derivatives of that object
• Polymorphism adjusts an object or value to match a specified property without being destructive
• Getters and setters are used to read and write properties on objects
• Inheritances can be used to override properties of instances of prototypes but the use of them is controversial
Chapter 17. Speaking - Objects and Inheritance • There are 4 layers of objects in JS: single objects, prototype chains of objects, constructors, and subclassing • All objects are dictionaries (like a hash) where every key/value pair is a property. Keys are always strings and values can be anything. • Named properties are most common where the string key points to a value. Accessors (getters/setters) are a second type of property. Internal properties also exist but are generally only accessible via the getPrototypeOf method • Use the "dot" to call methods, access properties, and get/set or delete properties • Methods can also be called with the bracket operator • This chapter reviews a lot of what was covered in Chapters 5 and 6 of Eloquent JavaScript, though with a few more thorough examples. • Section 2 has a nice summary of best practices for iterating through properties and enumerating • Defining a property is creating a new property whereas assigning a property is changing an existing property • Properties can be protected with various methods which determine how or if they can be altered • The later half of this chapter will need to be reviewed and re-read several times as I better understand Javascript; This portion of the chapter will be great to reference as I work with constructors and inheritance
Javascript Garden
• Right off the bat, this will be a great resource to keep around as it is a little clearer and more succinct than the chapters above. Especially while starting out, I think this is the most useful tool I've read through so far.
• All objects in js are technically hash maps or dictionaries so I would access properties just as I would a hash in ruby.
• Good recap of functions- what they are and how to use
• Also good recap of this
which often confuses me; Come back to this section!
• Overall good quick lookup type resource
Module 4 Intermission Assignments
Readings
Functions
Minimum function min(num1, num2){ if (num1 > num2) return num1; } else { return num2; }
Recursion function isEven(num){ if (num === 0) return true; } else if { num < 0 return false; } else { num - 2; isEven(num); } console.log(isEven(50)); -> true console.log(isEven(75)); -> false console.log(isEven(-1)); -> false
Bean Counting function countBs(string){ var counter = 0; for (var i = 0, i < string.length, ++) counter ++ if ( i === “B”); return counter; } console.log(countBs("BBC")) -> 2
function countChar(string, letter) { var counter = 0 ; for (var i = 0, string.length, ++) counter ++ if ( i === letter); return counter; } console.log(countChar("kakkerlak", "k"))
Higher order Functions
-Abstractions hide details and give us the ability to talk about problems at a higher level. -Higher order functions operate on other functions either by taking them as arguments or returning them -Reminder - JSON = javascript object notation what -reduce :)
The Secret Life of Objects
-methods are simply properties that hold function values -almost all object have a prototype or another object that is used as a fallback source of properties -calling a function with the ‘new’ keyword in front of it causes it to be treated as a constructor
JavaScript Garden -great resource for common javascript problems. It also has easy to read samples.
You can use [] notation in place of dot notation. Especially if dot notation isn't working.
.delete removes things from objects by key like Object["cat_name"].delete who then render Object["cat_name"] void of that key
objects will return thier contents when called
Chinese boxes are phyically impossibly but work in programing
range(start, end) takes two arguments. the first is optional
Split(" ") breaks a string on " ".
slice(from, too) copies from index to index not including the last one
objects dont == themselves even if they have the same value. Cause they arent the same object.
Date(year, month, day, hour, minute, seconds.....)
Arguments is an object. You can .length it
Math.
for(method in object) do this stuff
this
points to an object that a method is called on.Javascript is functional and object-oriented. I think this is extremely cool, because whenever I’ve researched languages, it seems like I always have to pick one that is either functional OR object oriented, but I don’t have to worry about that with Javascript. It’s both.
Function declarations in Javascript are not top-to-bottom read. This is important to know because we could then write code in a way that is clearer to us, as coders, but still functions correctly.
Passing the correct number of arguments to a function in Javascript can be tricky, because the language is very permissible to having too many or too few arguments, and will mostly not tell you about it, if you put in the incorrect amount. Be careful here.
You can pass actions as function values. function forEach(array, action) { for (var i = 0; i < array.length; i++) action(array[i]); }
Higher order functions are extremely versatile. You can use functions to create new functions. You can use functions to change functions. You can even use functions to make new types of flow control. Very cool.
Javascript has methods like Ruby, and It’s up to me to find them and make the best use of them.
Constructors can be used to create objects for object oriented programming in javascript.
example: function Rabbit(type) {
this.type = type;
}
var killerRabbit = new Rabbit("killer"); var blackRabbit = new Rabbit("black"); console.log(blackRabbit.type); // → black
Getters and Setters can be used to “specify a function to be run when the property is read or written”. This seems like it will come in handy in the future, and is something I need to remember. Mainly used in an object literal.
When talking about single objects there are dot operators and bracket operators ( I think I prefer dot operators because it is closer to ruby, and seems very straight forward).
Javascript as a whole can sometimes be a funky language, but it looks and seems very fun to write and play around with. I look forward to getting more in-depth with this language in the next weeks and months of my life!
In a comment on this issue, state what you found to be a valuable thing you read from Eloquent JavaScript.
Please use this github issue as a forum to ask and answer questions you came across in the from the reading.