- bits
- any kind of two-valued things, usually described as zeroes and ones.
- any piece of discrete information can be reduced to a sequence of zeros and ones and thus represented in bits.
- values
- chunks of bits that represent pieces of information (easier to manage as values rather than bits)
- all values are made of bits
- six basic types of values in javascript
- numbers
- strings
- booleans
- objects
- functions
- undefined vals
- each value takes up memory -- e.g., a certain number of bits. once you're done with a value, GC removes the value from memory.
- numbers
- numeric values
- javascript uses a fixed number of bits to store a single number val: 64
- fractional digital numbers in js are more of an approximation as bits are used to store the decimal, and w/ only 64 bits available, a number like pi wont be exact
- operators
+ - * / %
- strings
- represent text
- booleans
- t/f
- comparisons
- e.g.
< > <= >= === !==
etc
- e.g.
- logical operators
- and or not
&& || !
||
can be used as a fallback operator. e.g."Carl" || undefined
returns"Carl"
(second value never gets evaluated if first value passses)&&
works similarly but in reverse. e.g."Carl" && undefined
returnsundefined
andfalse && "hay girl"
returnsfalse
(second value never gets evaluated)
- and or not
- automatic type conversion
- js goes out of its way to accept input so it will do weird things like
false == 0 //-> true
and8 * null //-> 0
- using
=== !==
asks whether two things are precisely equal, preventing automatic type conversion
- js goes out of its way to accept input so it will do weird things like
- undefined vals
undefined null
- expressions and statements
- expression
- fragment of code / anything that produces a value
- an expession corresponds to a sentence fragment; a statement corresponds to a full sentence in human language
- a program is a list of statements
- e.g.
1;
orfalse;
- expression
- variables
- catch and hold values
- keywords and reserved words
-
do else false finally for function if implements in instanceof interface let new null package private protected public return static switch throw true try typeof var void while with yield this```
- environment
- the collection of variables and their values that exist at a given time
- environment isn't empty when a program starts (e.g. variables that are part of the language standard; ways to interact with the system)
- function
- piece of program wrapped in a value
- e.g.
alert
holds a function that shows a dialogue box - executing a function is to invoke, call, or apply it
- arguments
- values given to functions
- block
- sequence of statements wrapped in braces
do
loop- always executes its body at least once
- e.g.
do { var name = prompt('who art thou?'); } while (!name);
-- will only check thewhile
condition after thedo
block has executed once
- breaking out of
for
loopbreak
-- immediately jumps out of the enclosing loopcontinue
-- control jumps out of the body and continues with the next iteration of thefor
loop
switch
- alternative to
if else
etc - e.g.
switch (prompt("What is the weather like?")) { case "rainy": console.log("Remember to bring an umbrella."); break; case "sunny": console.log("Dress lightly."); case "cloudy": console.log("Go outside."); break; default: console.log("Unknown weather type!"); break; }
- alternative to
- functions
funciton(parameters) { body; }
- declarations
- create a function value
var hi = function() { console.log('hi'); }
- declare a function
function hi() { console.log('hi'); }
- function declarations (e.g. the one above) are not part of the regular top-to-bottom flow of control. they are conceptually moved to the top of their scope and can be used by all the code in that scope.
- e.g.
hi(); funciton hi() { console.log('hi'); };
would work
- e.g.
- don't define a function in an
if
block or loop- e.g.
if ( true ) { function b() {} }
- e.g.
- create a function value
- call stack
- related to control flow, where a computer stores the context of where it was before it called a function
- whenever a func is called, the current context is put at the top of the 'stack'. when the func returns, it removes the top context from the stack and uses it to continue execution
- an infite loop will use up all the stack's space, or blow the stack
- see here
- closure
- the ability to reference and single instance of local variables in an enclosing function
- e.g.
function wrapVal(n) { console.log(n); }
- e.g.
- a function that 'closes over' some local vars is called a closure
- the ability to reference and single instance of local variables in an enclosing function
- recursion
- when a func calls itself
- comebackto this func
- side effects vs return value funcitons
- some funcs are called for their side effects, others for their return value
- a pure function is one that has no side effects and returns a value
- objects
- allow us to group values—including other objects—together and thus build more complex structures
in
operator- can be used to find out whether an object contains a property with a given name (e.g.
var sarah = 'me'; 'sarah' in window //true
) - can also be used in a
for
loop (for (var name in object)
) to loop over an object’s properties
- can be used to find out whether an object contains a property with a given name (e.g.
- data sets
- array
- store sequences of values
- object
- store key value pairs
- array
- properties
- almost all js values have properties. for e.g. a string's length is a property
null
doesn't have properties- how to access properties? usually with either
.
or[]
e.g.'sarah'.length
or[0,2,3][0]
- methods
- properties that contain functions are referred to as methods.
- e.g.
toUpperCase
is a method of a string.push
is a method of an array.
- mutability
- the content of a value in an object can be modified by changing its properties
var obj1 = {hi: 'you'}; var obj2 = obj1; obj1.hello = 'yes?'; console.log(obj2.hello); //-> 'yes?' // obj1 and obj2 grasp the same object
- fundamental array methods
push
- add item to end of array
unshift
- add item to beg. of array
shift
- remove item to beg. of array
indexOf
andlastIndexOf
- both take an optional second argument that indicates where to start searching from.
slice
- takes a start index and an end index and returns an array that has only the elements between those indices. the start index is inclusive, the end index exclusive.}
- strings and their properties
slice
indexOf
- can take a string of multiple characters, e.g.
console.log('street'.indexOf('ee')); // 3
- can take a string of multiple characters, e.g.
trim
- removes whitespace
charAt
or[]
- to get char at a position
- arguments object
- Whenever a function is called, a special variable named arguments is added to the environment in which the function body runs
- refers to an object that holds all of the arguments passed to the function
- like an array but it's not!
- Whenever a function is called, a special variable named arguments is added to the environment in which the function body runs
- math object
random
- gives random num b/t 0 and 1- has
cos
sin
tan
andPI
-- lotsa trig for when ya need it floor
- rounds down to nearest whole numceil
- rounds up to nearest whole num
- global object
- global scope, the space in which global variables live -- can also be approached as an object in JavaScript
- global vars are present as a property of this object
- for e.g. in browsers, the global scope object is stored in the window variable
- size >> complexity >> confusion >> bugs
- abstracting functions / tasks makes things easier to read, harder to mess up
- higher-order functions
- functions that operate on other functions, either by taking them as arguments or by returning them
- can have functions that...
- create new funcs
- change other funcs
- provide new types of control flow
- e.g.
forEach
to do something with each element in an arrayfilter
to build a new array with some elements filtered outmap
to build a new array where each element has been put through a functionreduce
to combine all an array’s elements into a single value
- passing along arguments
apply
- allows you to pass a func an array(-like obj) of arguments, and call the func with those args
- json
- data storage/communication format for the web
- all property names have to be surrounded by double quotes
- only simple data expressions are allowed
- no function calls, variables, or anything that involves actual computation
- comments are not allowed
JSON.stringify
- takes a JavaScript value and returns a JSON-encoded string
JSON.parse
- takes such a string and converts it to the value it encodes
- binding
- all functions have this
- binding creates a new function that will call the original function but with some of the arguments already fixed
- used to create a partially applied version of the function
- methods
- properties that hold function values (eg
object.method()
) this
will point to the object it was called uponapply
andbind
methods both take a first argument that can be used to simulate method calls. This first argument is in fact used to give a value to this- there's also
call
, takes arguments normally (rather than array). still takes a specificthis
value
- properties that hold function values (eg
function speak(line) {
console.log("The " + this.type + " rabbit says '" +
line + "'");
}
var whiteRabbit = {type: "white", speak: speak};
var fatRabbit = {type: "fat", speak: speak};
whiteRabbit.speak("Oh my ears and whiskers, " +
"how late it's getting!");
// → The white rabbit says 'Oh my ears and whiskers, how
// late it's getting!'
fatRabbit.speak("I could sure use a carrot right now.");
// → The fat rabbit says 'I could sure use a carrot
// right now.'
speak.apply(fatRabbit, ["Burp!"]);
// → The fat rabbit says 'Burp!'
speak.call({type: "old"}, "Oh my.");
// → The old rabbit says 'Oh my.'
- prototypes
- functions derive from
Function.prototype
, arrays fromArray.prototype
, objects fromObject.prototype
etc Object.getPrototypeOf
- returns the prototype of an object
- `Object.create
- create an object with a specific prototype
- a way to create objects that derive from some shared prototype is to use a constructor
- functions whose names usually start with a capital letter
- calling a function with the
new
keyword in front causes it to be treated like a constructor this
variable will be bound to a fresh object- obj created with
new
is said to be an instance of the constructor - capitalize names of constructors
- constructors automatically get a property named
prototype
, which by default holds a plain, empty object that derives fromObject.prototype
- functions derive from
- *overriding derived properties
- when you add a property to object itself, it doesn't change the values given in the prototype
function Rabbit(type) {
this.type = type;
}
var killerRabbit = new Rabbit('killer');
var blackRabbit = new Rabbit("black");
Rabbit.prototype.teeth = 'small';
killerRabbit.teeth = 'long bloddy sharp';
blackRabbit.teeth; // small
-
Directly calling Object.prototype.toString with an array -- that function doesn’t know about arrays, so it simply puts the word “object” and the name of the type between square brackets, eg
var o = {hi: 'you'}; o.toString() //"[object Object]"
-
prototype interference
- prototype can be used at any time to add new properties and methods to all objects based on it
- js distinguishes between enumerable and nonenumerable properties
defineProperty
- allows us to control the type of property we are creating, eg
Object.defineProperty(Object.prototype, "hiddenNonsense", {enumerable: false, value: "hi"});
- allows us to control the type of property we are creating, eg
hasOwnProperty
- tells us whether the object itself has the property, without looking at its prototypes
-
prototype-less objects
- if you dont want prototype, you can do
var map = Object.create(null);
map["pizza"] = 0.069;
console.log("toString" in map);
// → false
console.log("pizza" in map);
// → true
- polymorphism
- having different objects expose the same interface and then writing code that works on any object with the interface
- polymorphic code can work with values of different shapes, as long as they support the interface it expects
- getters and setters
- when a getter but no setter is defined, writing to the property is simply ignored
- in object literal, the
get
orset
notation for properties allows you to specify a function to be run when the property is read or written - can also add such a property to an existing object, for example a prototype, using the
Object.defineProperty
function
Object.defineProperty(TextCell.prototype, "heightProp", {
get: function() { return this.text.length; }
});
- inheritance
- when you create an object from another object's prototype
- somewhat controversial
- can be confused with polymorphism, overused in ugly ways
- can have polymorphism without inheritance
- inheritance fundamentally ties types together, can be confusing/tangled
- not something to avoid, but rather to use with understanding
- can be confused with polymorphism, overused in ugly ways
- the instanceof operator
- binary operator
- will see through inherited types
- see here
🆒