• Programming Languages

  • Python

    Python is a strongly-typed, dynamically typed multi-paradigm language created by Guido Van Rossum.

  • JavaScript

    Javascript is a dynamic, untyped, object-oriented prototypal language created by Brendan Eich.

  • R

  • Software Development

  • Requirements Checklist

  • Functions

    Functions look like this:

    def aFunction(params):
        print "Do something"
        return 1

    All functions return a value.

  • Code Blocks/Indentation

    Code blocks are denoted by indentation. PEP8 specifies that indents should be 4 spaces.

  • Objects

    Everything, including functions, are objects in Python.

  • List Comprehensions

    [aFunction(elem) for elem in aList]

    Will return a new list:

    “It is safe to assign the result of a list comprehension to the variable that you’re mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable.”

  • String Methods

    .lower( )

    .upper( )

    .join(aList ) - join any list of strings into a single string. Handy when used in conjunction with list comprehensions.

    .split(aDelimiter, timesToSplit) - splits a string into a list given a delimeter

  • Dicts

    keys() - returns list of all keys (in a particular order, but not necessarily order of definition)
    values() - returns list of all values: same order as keys()
    items() - returns a list of tuples of the form (key,value)

  • Speaking JavaScript

  • Professional: JavaScript for Web Developers

    Nicholas C. Zakas

  • Notes

    Function expressions are not hoisted, so order matters!

    The return value of a constructor will be the value returned when called by new

  • swirl : R Programming

  • Functional Requirements

  • Quality Requirements

  • Requirements Quality

  • Completeness

  • Built-In Functions

    type( ) - returns datatype of an object. Possible types are listed in the types module.

    str( ) - coerces data into a string
    Gotchas: string representation of modules includes the pathname of the module on disk.

    dir( ) - returns list of attributes and methods of any object

    callable( ) - returns True if object is callable as a function, False if not. Functions, methods, and classes count as callable.

    getattr(object, callablename, defaultvalue) - returns a reference to a function or method. Works on functions and methods from modules, and on lists and dicts, but not tuples (which have no methods).

  • Doc Strings

    A function’s doc strings are accessible as str types via the __doc__ attribute.

    print aFunction.__doc__
  • Search Path

    The library search path is defined in sys.path as a list.

  • Modules

    You can get the module name with the __name__ attribute. This is commonly used to check if the current script is running as a standalone program:

    if __name__ == "__main__"

    This is good to use for writing/running test suites for a class or script.

  • 3. The Nature of JavaScript

    Dynamic.
    Dynamically typed.
    Functional and object oriented.
    Fails silently.
    Deployed as source code.
    Part of the web platform.

    Quirks

    No block-scoped variables
    No built-in modules
    No support for subclassing
    No integers (engines optimize this)
    Arrays too flexible (engines optimize this)

    Elegant Parts

    First class functions
    Closures
    Prototypes
    Object literals
    Array literals

    Influences

    Java - syntax
    AWK - functions
    Scheme - first-class functions and closures
    Self - prototypal inheritance
    Perl/Python - strings, arrays, regex
    HyperTalk - integration into web browsers, event handling attributes in HTML

  • Netscape originally hired Brandan Eich to implement Scheme in the browser. But then Netscape partnered with Sun to bring Java to the browser. Because of that, JavaScript needed to have syntax similar to Java.

    JavaScript’s first name was Mocha. It was renamed to LiveScript before the final name, JavaScript was adopted.

  • 7.JavaScript’s Syntax

    Basic expressions and statements
    Comments
    Expressions versus statements
    Control flow statements and blocks
    Rules for using semicolons
    Legal identifiers
    Invoking methods on number literals
    Strict mode

  • 8. Values

    JavaScript’s Type System
    Primitive Values Versus Objects
    Primitive Values
    Objects
    undefined and null
    Wrapper Objects for Primitives
    Type Coercion

  • 9. Operators

    Operators and Objects
    Assignment Operators
    Equality Operators: === Versus ===
    Ordering Operators
    Plus Operator +
    Operators for Booleans and Numbers
    Special Operators
    Categorizing Values via typeof and instanceof
    Object Operators

  • 10. Booleans

    Converting to Boolean
    Logical Operators
    Equality Operators, Ordering Operators
    The Function Boolean

  • 11. Numbers

    JavaScript treats all numbers as 64-bit IEEE-754 numbers. JavaScript engines may optimize for integers internally.

    Number Literals
    Converting to Number
    Special Number Values
    The Internal Representation of Numbers
    Handling Rounding Errors
    Integers in JavaScript
    Converting to Integer
    Arithmetic Operators
    Bitwise Operators
    The Function Number
    Number Constructor Properties
    Number Prototype Methods
    Functions for Numbers

  • 12. Strings

    String Literals
    Escaping in String Literals
    Character Access
    Converting to String
    Comparing Strings
    Concatenating Strings
    The Function String
    String Constructor Method
    String Instance Property length
    String Prototype Methods

  • 13. Statements

    Declaring and Assigning Variables
    The Bodies of Loops and Conditionals
    Loops
    Conditionals
    The with Statement
    The debugger Statement

  • 14. Exception Handling

    What is Exception Handling?
    Exception Handling in JavaScript
    Error Constructors
    Stack Traces
    Implementing Your Own Error Constructor

  • 15. Functions

    The Three Roles of Functions in JavaScript
    Terminology: “Parameter” Versus “Argument”
    Defining Functions
    Hoisting
    The Name of a Function
    Which Is Better: A Function Declaration or a Function Expression?
    More Control over Function Calls: call(), apply(), and bind()
    Handling Missing or Extra Parameters
    Named Parameters

  • 16. Variables: Scopes, Environments, and Closures

    Declaring a Variable
    Background: Static Versus Dynamic
    Background: The Scope of a Variable
    Variables Are Function-Scoped
    Variable Declarations Are Hoisted
    Introducing a New Scope via an IIFE
    Global Variables
    The Global Object
    Environments: Managing Variables
    Closures: Functions Stay Connected to Their Birth Scopes

  • 17. Objects and Inheritance

    Layer 1: Object-orientation with single objects
    Layer 2: Prototype chains of objects
    Layer 3: Constructors as factories for instances
    Layer 5: Subclassing & Subconstructors

  • 18. Arrays

    Overview
    Creating Arrays
    Array Indices
    length
    Holes in Arrays
    Array Constructor Method
    Array Prototype Methods
    Adding and Removing Elements (Destructive)
    Sorting and Reversing Elements (Destructive)
    Concatenating, Slicing, Joining (Nondestructive)
    Searching for Values (Nondestructive)
    Iteration (Nondestructive)
    Best Practices: Iterating over Arrays

  • 2. JavaScript in HTML - Review Questions

    • What are the six attributes for the script element?
      • Which ones are optional, required, or depreciated?
      • Which ones are valid for inline scripts?
      • What does each one do?
    • What is an inline script?
      • What are restricted character strings in an inline script? What’s the workaround?
      • How does an inline script affect display/interpretation of the rest of the page content in a browser?
    • What is an external script?
      • What attributes are required for an external script?
      • What is the syntax for an external script?
      • JavaScript files need a .js extension?
    • In what order are script elements executed by default?
      • How do defer and async affect script execution?
    • What was the rationale for putting script elements in the <head> part of the document, and what are the drawbacks?
    • Where do modern webapps commonly put script elements, and why?
    • According to the HTML specification, when (in what order & before and after what DOM elements) are deferred scripts executed?
    • How do you specify a defer attribute in an XHTML tag?
    • What steps should you take when you embed inline scripts in XHTML documents?
    • When is XHTML mode triggered in a browser?
    • What are the three main arguments for primarily using external files?
    • What document modes exist for most browsers?
    • When is Quirks Mode triggered?
    • What is the difference between Standards Mode and Almost Standards Mode?
    • When is content contained in a <noscript> element displayed?
  • 3. Language Basics Review Questions

    Syntax

    • JavaScript is specified (syntax, operators, data types, built-ins) in what standard? What is the name of the pseudolanguage description used in the standard?
    • What is the latest standard for JavaScript?
    • What versions of the JavaScript standard do the following engines support? Which one(s) support the most advanced features?
      • Chakra
      • JavaScriptCore (Nitro)
      • JScript 9.0
      • KJS
      • Spider Monkey
      • V8
    • True or false: an identifier in JavaScript that is an uppercase or lowercase version of a reserved word cannot be used.
    • What are valid first characters of an identifier?
    • What are valid subsequent characters for an identifier?
    • What kinds of comments does JavaScript support?
  • 3. Language Basics

    • Syntax
    • Keywords and Reserved Words
    • Variables
    • Data Types
    • Operators
    • Statements
    • Functions
  • 4. Variables, Scope, and Memory

    • Primitive and Reference Values
    • Execution Context and Scope
    • Garbage Collection
  • 5. Reference Types

    Objects are instances of a particular reference type. Reference types are also sometimes called object definitions.

    Reference types are not classes. JavaScript does not have classes. A new object instance is created with the new operator.

    var butt = new Thing();

    ECMAScript provides a bunch of built-in reference classes.

    • The Object Type
    • The Array Type
    • The Date Type
    • The Regexp Type
    • The Function Type
    • Primitive Wrapper Types
    • Singleton Built-In Objects
  • 6. Object-Oriented Programming

  • Basic Building Blocks

  • Workspace and Files

    getwd
    setwd
    list.files / dir
    args
    dir.create
    file.create
    file.exists
    file.info
    file.rename
    file.copy
    file.path
    dir.create
    unlink

  • Sequences of Numbers

    ?
    :
    length
    seq
    seq(along.with = ... )
    seq_along
    rep(n, times = ..., each = ...)

  • 4. Vectors

  • 5. Missing Values

    NA
    NaN
    is.na
    rnorm
    rep
    sample

  • 6. Subsetting Vectors

    x[is.na(x)]
    x[-2]
    x[c(-2,-10)]
    x[-c(2,10)]
    vect <- c(foo = 11, bar = 2, norf = NA)
    names(vect)
    vect2 <- c(11, 2, NA)
    names(vect) <- c("foo", "bar", "norf")
    identical(vect, vect2)
    vect["bar"]
    vect[c("foo", "bar")]
  • 7. Matrices and Data Frames

    my_vector <- 1:20
    dim(my_vector)
    length(my_vector)
    dim(my_vector) <- c(4,5)
    attributes(my_vector)
    class(my_vector)
    my_matrix2 <- matrix(1:20, nrow = 4, ncol = 5)
    patients <- c("Bill", "Gina", "Kelly", "Sean")
    cbind(patients, my_matrix)
    my_data <- data.frame(patients, my_matrix)
    cnames <- c("patient", "age", "weight", "bp", "rating", "test")
    colnames(my_data) <- cnames
  • 8. Logic

  • 9. Functions

  • 10. lapply and sapply

  • 11. vapply and tapply

  • 12. Looking at Data

  • 13. Simulation

  • 14. Dates and Times

  • 15. Base Graphics

  • Basic expressions and statements

  • Comments

  • Expressions versus statements

  • Control flow statements and blocks

  • Rules for using semicolons

  • Invoking methods on number literals

  • Strict mode

    Switching on strict mode
    Caveats on using strict mode
    Functions in strict mode
    Setting and deleting immutable properties fails with an exception in strict mode
    Unqualified identifiers can’t be deleted in strict mode
    Features that are forbidden in strict mode

  • JavaScript’s Type System

    JavaScript’s Types - JavaScript has six types: undefined, null, Boolean, Number, String, and Object.

    Static Typing Versus Dynamic Typing/Type Checking - JavaScript is dynamically typed (types not known until runtime). It only does dynamic type checking when trying to use a property of null or undefined.

    Coercion - most operands convert operands to a primitive type — Boolean, Number, String, and Object.

  • Primitive Values Versus Objects

    booleans, numbers, strings, null, and undefined are primitive types. Everything else in JavaScript is an object. Objects are only strictly equal (===) to themselves. All primitive types are equal if they contain the same value.

  • Primitive Values

    Booleans: true, false
    Numbers: IEEE-754 floating point, 64-but
    Strings: Unicode characters surrounded by quotes
    Undefined: undefined
    Null: null (typeof returns Object)

    Primitives are compared by value and are immutable. You cannot define new primitive types.

  • Objects

    All nonprimitive values are Objects. The most common kinds of objects are plain objects, arrays, and regular expressions.

    Objects are compared by reference, mutable by default, and extensible by the user.

  • undefined and null

    undefined means no value, and uninitialized variables, missing parameters/properties have this value. Functions return undefined by default.

    null means no object. It is the last element in the prototype chain and gets returns if there is no match for a regular expression.

    You can check for them specifically by strict inequality or by implicit conversion to Boolean in a control statement.

    Trying to access properties for either leads to an exception (this is the only case).

    undefined can be changed in ECMAScript 3 and earlier. It is read-only in ES5+.

  • Wrapper Objects for Primitives

    Boolean, Number, and String have wrapper objects. Primitive values borrow methods from these wrapper objects.

    Wrapper objects are usually only used implicitly, or for conversion. Creating new wrapper objects with a constructor should especially be avoided.

  • Type Coercion

    JavaScript operators force a implicit conversion of operands to an expected primitive type. JavaScript uses an internal function, ToPrimitive() to do the conversion.

    To perform conversion to a different type, use Boolean(), Number(), String(), and Object().

  • Operators and Objects

    All operators in JavaScript coerce operands to expected primitive types. This conversion sometimes causes unexpected behavior for programmers familiar with other languages—notably, arrays cannot be concatenated via operator because they are coerced to strings first. You cannot define or overload the behavior of operators in JavaScript.

  • Equality Operators: === Versus ==

    When testing for equality, always use === over ==.

    NaN is the only value that is never equal to itself.

  • Special Operators

    The void operator is a unary operator that always evaluates an expression to undefined. It’s notably used for javascript: URLs in the browser. It can also be used for IIFEs.

  • Number Literals

    Integer, float, or hexadecimal.

  • Converting to Number

    Manually convert with Number(value) or +value.

    parseFloat(str, radix?) extracts the first valid floating point numeric string it finds from a string, ignoring whitespace. It parses '' as NaN. It is usually better to use Number().

  • Special Number Values

    NaN is a number value that is not equal to anything, including itself. It gets produced when number conversions/operations fail. You can check for NaN with isNaN( ), but you should also do a type check since isNaN( ) will coerce non-numbers.

    Infinity: Infinity and -Infinity. Numbers outside the range Number.MAX_VALUE and Number.MIN_VALUE, as well as values divided by zero become +/- Infinity. Check for Infinity with strict equality and isFinite( ).

    JS has both positive and negative zero, in accordance with IEEE-754. In most cases, they are indistinguishable. Numbers that approach zero beyond the precision supported become +/- 0 depending on their previous value. Math.pow(x, -1), `Math.atan(x, -1), and division by the zero reveal the sign of the zero.

  • The Internal Representation of Numbers

    64-bit precision:

    • bits[53] sign
    • bits[62-52]
    • bits[51-0] fraction
  • Handling Rounding Errors

    Decimal (non-binary) fractions create rounding errors. To compare non-integers, determine equality using an epsilon. The standard machine epsilon is 2^-53

  • Integers in JavaScript

    Safe signed integers: (-2^53, 2^53) or (Number.MIN_SAFE_INTEGER, Number.MAX_SAFE_INTEGER)

    Array indices: [0, 2^32-1]
    UTF-16 codes: 16 bits, unsigned

    For a binary operator on integers, you must check both integers and the result to determine if it is safe.

  • Converting to Integer

    Math.floor() Math.ceil() Math.round()

    Convert to 32-bit integers via bitwise |0 and shift operators.

    parseInt(str, radix?) gets

  • Arithmetic Operators

  • Bitwise Operators

  • The Function Number

  • Number Constructor Properties

  • Number Prototype Methods

  • Functions for Numbers

  • String Literals

    Single quoted and double quoted strings are equivalent.

  • Escaping in String Literals

    Line continuations - backslash and plus operator

    Character escape sequences
    NUL character
    Hexadecimal escape sequences for characters
    Unicode escape sequences

  • Character Access

    String.charAt(i)

  • Converting to String

    String( )
    ''+value
    value.toString()
    JSON.stringify(value, replacer?, space?)

  • Comparing Strings

    comparison operators
    String.prototype.localeCompare( )

  • Concatenating Strings

    +
    Adding to array then joining

  • The Function String

    String( v )

  • String Constructor Method

    String.fromCharCode( c1, c2, ... )
    String.prototype.charCodeAt( i )

  • String Instance Property length

    Number of characters in string. Immutable. Characters represented by escape codes are counted as one character.

  • String Prototype Methods

    Extract Substrings
    Transform
    Search and Compare
    Test, Match, and Replace with Regular Expressions

  • Declaring and Assigning Variables

    var declares a variable. Variable declarations are hoisted. = assigns. They can be combined.

  • Loops

    Loop body is a single statement or a code block.

    [label]:
    break continue

    while
    do-while
    for
    for-in (use Array.prototype.forEach( ) for Arrays)
    for-each-in (Firefox only)

  • Conditionals

    if-then-else
    switch

  • The with Statement

    Depreciated!

  • The debugger Statement

    debugger;

  • Exception Handling in JavaScript

    throw
    try-catch-finally

    At least throw a new Error( ... ) instead of a string. Environments may provide a stack trace with the error object.

  • Error Constructors & Properties

    Error
    EvalError - not used
    RangeError
    ReferenceError
    SyntaxError
    TypeError
    URIError

    Properties
    message
    name
    stack

  • Stack Traces

    You can set the message property of the error. Engines may support the stack property.

  • Implementing Your Own Error Constructor

  • The Three Roles of Functions in JavaScript

    Nonmethod function (“normal function”)
    Constructor
    Method

  • Terminology: “Parameter” Versus “Argument”

    parameters - (formal parameters/arguments) used in the function definition

    arguments - (actual parameters/arguments) in the function invocation

  • Defining Functions

    Function Expressions - anonymous or named
    Function Declarations - hoisted
    The Function Constructor - Similar to eval. Don’t use this in general.

  • Hoisting

    Only function declarations are completely hoisted. var is hoisted, but assigning a function expression is not.

  • The Name of a Function

    Most JS engines support the property name, which is useful for debugging.

  • Which Is Better: A Function Declaration or a Function Expression?

  • More Control over Function Calls: call(), apply(), and bind()

    func.apply(thisValue, argArray)
    func.bind(thisValue, arg1, ..., argN)

  • Handling Missing or Extra Parameters

    More actual parameters than formal parameters - extra parameters ignored but are still in arguments

    Fewer actual parameters than formal parameters - missing parameters get undefined

    arguments - array-like object—has length and can access elements with [] but no other array methods.

    Strict vs Sloppy mode: callee property is depreciated and is not allowed in strict mode. In sloppy mode, arguments change when parameters change, but not in strict mode. Strict mode prevents assigning to arguments.

    Mandatory Parameters, Enforcing a Minimum Arity

    Optional Parameters

    Simulating Pass-by-Reference Parameters - enclose in an array.

    Pitfall: Unexpected Optional Parameters

  • Named Parameters

    JavaScript doesn’t support named parameters directly. Simulate by passing in an object.

  • Declaring a Variable

  • Background: Static Versus Dynamic

    Statically (or lexically)
    Dynamically

  • Background: The Scope of a Variable

    The scope of a variable
    Lexical scoping
    Nested scopes
    Shadowing

  • Variables Are Function-Scoped

  • Variable Declarations Are Hoisted

  • Introducing a New Scope via an IIFE

    It is immediately invoked
    It must be an expression
    The trailing semicolon is required

    IIFE Variation: Prefix Operators
    IIFE Variation: Already Inside Expression Context
    IIFE Variation: An IIFE with Parameters
    IIFE Applications

  • Global Variables

    PITFALL: ASSIGNING TO AN UNDECLARED VARIABLE MAKES IT GLOBAL

  • The Global Object

    Brandon Eich considers the global object one of his biggest regrets.

    Browsers - window - standardized as part of the DOM, not ES5
    Node.js - global

    Use Cases for window

  • Environments: Managing Variables

    Dynamic dimension: invoking functions - stack of execution contexts

    Lexical (static) dimension: staying connected to your surrounding scopes - chain of environments

  • Closures: Functions Stay Connected to Their Birth Scopes

    Handling Closures via Environments

  • Cheat Sheet: Working With Objects

  • Layer 1. Object-orientation with single objects

    Kinds of Properties
    Object Literals
    Dot Operator
    Unusual Property Keys
    Bracket Operator
    Converting Any Value to an Object

  • this as an Implicit Parameter of Function and Methods

    call( ), apply( ), bind( )
    apply( ) for constructors
    pitfall: losing this when extracting a method
    pitfall: functions inside methods shadow this

  • Layer 2. Prototype chains of objects

    Inheritance. Overriding. Sharing data between objects via a prototype. Getting and setting the prototype. __proto__. Setting and deleting affects only own properties.

    Iteration and Detection of Properties. Listing own property keys. Listing all property keys. Checking whether a property exists.

    Best Practices: Iterating over Own Properties.

    Accessors (Getters and Setters). Defining accessors via an object literal. Defining accessors via property
    descriptors. Accessors and inheritance.

    Property Attributes and Property Descriptors. Property Attributes. Property Descriptors. Getting and Defining Properties via descriptors. Copying an object. Properties: definition versus assignment. Inherited read-only properties can’t be assigned to. Enumerability: best practices.

    Protecting Objects. Preventing extensions. Sealing. Freezing. Pitfall: protection is shallow.

  • Layer 3. Constructors as factories for instances

    What is a constructor in JavaScript? The new operator implemented in JavaScript. Terminology: the two prototypes. The constructor property of instances. The instanceof operator. Tips for implementing constructors.

    Data in Prototype Properties. Avoid prototype properties with initial values for instance properties. Avoid nonpolymorphic prototype properties. Polymorphic prototype properties.

    Keeping Data Private. Private data in the environment of a constructor (Crockford Privacy Pattern). Private data in properties with marked keys. Private data in properties with reified keys. Keeping global data private via IIFEs.

  • Layer 4. Subconstructors

    Overview

    Inheriting Instance Properties
    Inheriting Prototype Properties
    Ensuring That instanceof Works
    Overriding a Method
    Making a Supercall
    Avoiding Hardcoding the Name of the Superconstructor
    Example: Constructor Inheritance in Use
    Example: The Inheritance Hierarchy of Built-in Constructors
    Antipattern: The Prototype Is an Instance of the Superconstructor

    Methods of All Objects

    Conversion to Primitive
    Object.prototype.toLocaleString()
    Prototypal Inheritance and Properties

    Generic Methods: Borrowing Methods from Prototypes

    Accessing Object.prototype and Array.prototype via Literals
    Examples of Calling Methods Generically
    Array-Like Objects and Generic Methods
    A List of All Generic Methods

    Pitfalls: Using an Object as a Map

    Pitfall 1: Inheritance Affects Reading Properties
    Pitfall 2: Overriding Affects Invoking Methods
    Pitfall 3: The Special Property __proto__
    The dict Pattern: Objects Without Prototypes Are Better Maps
    Best Practices

  • Overview

    Array syntax
    Arrays Are Maps, Not Tuples
    Arrays Can Also Have Properties

  • Creating Arrays

    Array Literals/The Array Constructor
    Multidimensional Arrays

  • Array Indices

    indices i go from 0 ≤ i < 2^32−1
    max length is 2^32-1

    Indices out of range are treated as string property keys.

    The in Operator and Indices
    Deleting Array Elements
    Array Indices in Detail

  • length

    length only keeps track of the highest index. It doesn’t count nonholes.

    Trying to construct an array with length > 2^32-1 will cause a RangeError: Invalid array length.

    Manually Increasing the Length of an Array
    Decreasing the Length of an Array

  • Holes in Arrays

    Creating Holes
    Sparse Arrays Versus Dense Arrays
    Which Operations Ignore Holes, and Which Consider Them?
    Removing Holes from Arrays

  • Array Constructor Method

    Use Array.isArray(obj) instead of instanceof to detect Arrays.

  • Adding and Removing Elements (Destructive)

    Array.prototype.shift()
    Array.prototype.unshift(elem1?, elem2?, ...)
    Array.prototype.pop()

    Array.prototype.push(elem1?, elem2?, ...)
    Array.prototype.push.apply(thisValue, argArray)

    Array.prototype.splice(start, deleteCount?, elem1?, elem2?, ...)

    ``

  • Sorting and Reversing Elements (Destructive)

    Array.prototype.reverse()
    Array.prototype.sort(compareFunction?)

    Comparison functions should return the following:

    Result Return Value
    less than -1
    equal 0
    greater than 1

    Comparing Numbers

    Use conditional statements. Subtracting can cause overflow.

    Comparing Strings

    Use String.prototype.localeCompare

  • Concatenating, Slicing, Joining (Nondestructive)

    Array.prototype.concat(arr1?, arr2?, ...)

    Array.prototype.slice(begin?, end?)
    Will copy the array if no indices are provided.

    Array.prototype.join(separator?)
    Uses , as a default separator.

  • Searching for Values (Nondestructive)

    Array.prototype.indexOf(searchValue, startIndex?)
    Returns index of first match, or -1 if not found. Uses strict equality.

    Array.prototype.lastIndexOf(searchElement, startIndex?)
    Searches from startIndex to the beginning of the array.

  • Iteration (Nondestructive)

    Examination - forEach( ) every( ), some( )

    Transformation - map( ) filter( )

    Reduction - reduce( ) reduceRight( )

  • Best Practices: Iterating over Arrays

    1. Use a for loop
    2. Use array iteration methods (forEach(), some(), every(), map(), filter(), reduce(), reduceRight())

    Don’t use for-in, since that will iterate over all properties, not elements.

  • Data Types

    Data Type typeof( ) Description
    Undefined 'undefined' undefined; uninitialized/undeclared variables
    Null 'object' null
    Boolean 'boolean' true false
    Number 'number' integers, floating point, +/-Infinity, NaN
    String 'string' characters, character literals, empty strings
    Object 'object' JavaScript objects
  • Operators

    • Unary + -
    • Increment/Decrement ++ --
    • Bitwise ~ & | ^
    • Bitwise Shift << >> >>>
    • Logical (Boolean) ! && ||
    • Multiplicative * / %
    • Additive + -
    • Relational < > <= >=
    • Equality == != === !===
    • Assignment = *= /= += -= %= <<= >>= >>>=
    • Comma ,
  • Statements

    • if
    • do-while
    • while
    • for
    • for-in
    • break
    • continue
    • with
    • switch
  • Functions

    • Can be assigned to variables
    • Always return values. Default value is undefined
    • No function signatures
    • No overloading (last declared function overrides previous ones)

    Strict Mode

    • Functions and parameters cannot be named eval or arguments
    • No named parameters with the same name

    Arguments

    • Acts similar to argv
    • Interpreter won’t complain if function called with a different number of arguments than the declaration
    • Named parameter not passes in function call is assigned undefined
    • arguments object: acts like an array, but is not instance of Array
    var beets = function(){
      if (arguments) {
        if (arguments.length >= 3) {
          for (x in arguments) {
            console.log(x);
          }
        } else if (arguments.length === 2) {
          console.log('1. ' + arguments[0]);
          console.log('2. ' + arguments[1]);
        } else {
          console.log('only argument: ' + arguments[0]);
        }
      }
    }

    Arguments stay in sync with named parameters:

    • Change to named parameter will change corresponding argument
    • Not the other way around
  • Primitive and Reference Values

    Primitive values are accessed by value.

    Objects are accessed by reference.

    Dynamic Properties

    You can add properties to reference values at any time.
    Trying to add properties to primitive values won’t work, but also won’t cause an error.

    Copying Values

    Assigning a primitive value creates a new copy.
    Assigning a reference value passes the reference to the same object instance.

    Argument Passing

    Always passed by value—value is copied into a local variable. Passing by reference is not possible in JS. This functionality is replaced by closures.

    Determining Type

    typeof( ) returns the type of primitive values.
    variable instanceof Constructor returns true if X is an instance of reference type with constructor Constructor.

  • Execution Context and Scope

    Execution Context - defines access and behavior for a variable or function—what other data it can access. This is not accessible directly by code.

    An inner context can access variables in an outer context, but not the other way around.

    In web browsers, the global execution context is the window object. Each function has its own local execution context.

    The other primary type of context is the function execution context.

    Scope Chain provides access to all variables and functions in the execution context.

    The Variable Object is the front of the Scope Chain.

    In Functions the Activation Object is used as the variable object.

    Each context can search up the scope chain, but not down.

    • Scope Chain Augmentation - temporary addition to front of the scope chain, caused by catch and with
    • No Block-Level Scopes
  • Garbage Collection

    • Mark-and-Sweep - variables flagged in context when entering, flagged as out of context when leaving
    • Reference Counting - count references to an object/variable and deallocate when zero. Vulnerable to cyclic references. IE8 and earlier had non-native JS objects (DOM/BOM/COM) that used reference counting.
    • Performance -
    • Managing Memory - dereferencing global values by setting to null helps minimize memory usage
  • The Object Type

    Two ways to create an Object instance explicitly

    Object literal notation, and when it is used

    Expression context, statement context, how context affects interpretation of {

    Property names in object literal notation

    Creating an empty object

    Way to access object properties

    When bracket notation is favored

  • The Array Type

    Arrays can hold any data type at any index. (They are more similar to lists in Python than Arrays in Java.)

    There are two main ways to create arrays: the Array constructor and an Array literal.

    Array elements are accessed via index and square bracket.

    ben[1] = "helicopter";

    The number of elements in an array is given by the length property.

    The length property is mutable: decreasing length truncates elements from the end of the Array. Increasing length appends elements with the value of undefined to the end of the array.

    colors[colors.length] = "butt brown"; // appends value to end of array
    • Detecting Arrays
    • Conversion Methods
    • Stack/Queue Methods
    • Reordering Methods
    • Manipulation Methods
    • Location Methods
    • Iterative Methods
    • Reduction Methods
  • The Date Type

    ECMAScript Date represents dates as the number of milliseconds since midnight 1970-01-01 UTC.

    Create a new Date object with the new operator and the Date() constructor.

    Without arguments, the object is set to the current date and time.

    var now = new Date();

    Reference type methods

    Date.parse( dateString )

    Parses strings containing a date, returning the UTC date in milliseconds. The Date( ) constructor calls parse( ) if passed a string. Supports several formats as defined by ECMA-262 Fifth Ed.:

    • mm/dd/yyyy
    • Month_name dd, yyyy
    • Day_of_week Month_name dd yyyy hh:mm:ss Time_zone
    • yyyy-mm-ddThh:mm:ss.sssZ (ECMAScript 5 compliant implementations only)

    Returns NaN if the string can’t be parsed as a date (this happens when the date string doesn’t exactly match one of the supported patterns.)

    Date.UTC( y, m[, d, h, m, s, ms] )

    Returns the local timezone’s date in milliseconds for a specified UTC year, month, day, hour, minute, seconds, and milliseconds.

  • The Regexp Type

    Regular Expression literal:

    var exp = /{pattern}/{flags}

    Supported flags:

    • g : global
    • i : case insensitive
    • m : multiline

    RegEx Metacharacters

    ( [ { \ ^ $ | ) ] } ? * + .

    Metacharacters need to be escaped with \ if they are part of the pattern.

    RegEx Constructor

    var expression = /\$\( +\)\./gm;
    var equivExpression = new RegEx("\\$\\( +\\)\\.","gm");

    Note how metacharacters need to be double-escaped in the string.

    Differences between literal and constructor creation patterns

    In ECMAScript versions before 5, regular expression created as a literal will always reference the same RegExp instance (the instance properties remain in the same state.)

    A regular expression created with a constructor will always create a new RegEx instance.

    In ECMAScript 5, the literal pattern creates a new instance, like the RegEx constructor.

    input $_
    lastMatch $&
    lastParen $+
    leftContext $`
    multiline $*
    rightContext $'
  • The Function Type

    There are three main ways to define a function:

    Function-Declaration Syntax
    function f(args, bargs, dargs) {
    }
    Function Expression
    var f = function(args, bargs, dargs){
    };

    Note the need of a semicolon, since this is an expression and not a code block.

    Function Constructor
    var f = new Function('args', bargs', 'return args+bargs");

    Don’t use this. It causes double interpretation of code.

    Function names are pointers to function objects.

    This is why there is no overloading—declaring two functions with the same name just overwrites the earlier one with the later one.

    • Function Declarations versus Function Expressions
    • Functions as Values
    • Function Internals
    • Function Properties and Methods
  • Primitive Wrapper Types

    Allows primitive values to be treated as objects with methods.

    When a boolean, number, or string primitive value is accessed in read mode and a method is called, the following steps occur:

    1. Create instance of wrapper type
    2. Call method on instance
    3. Destroy instance

    Automatically created primitive wrapper types are destroyed immediately after use. This means that you cannot add properties or new methods to primitive types.

    Primitive wrappers can be explicitly created with constructors, but this should only be done in rare need. Any values created with the new operator and constructor will return typeof “object”.

    The Object constructor can return an instance of a primitive wrapper by passing in the primitive.

    var obj = new Object("a blah");
    console.log(obj instanceof String); // true
    • The Boolean Wrapper Type
    • The Number Wrapper Type
    • The String Wrapper Type
  • Singleton Built-In Objects

    • Global object
    • URI-encoding methods
    • eval()
    • Math
  • Understanding Objects

    • Types of Properties
    • Defining Multiple Properties
    • Reading Property Attributes
  • Object Creation

    • The Factory Pattern
    • The Constructor Pattern
    • The Prototype Pattern
    • Combination Constructor/Prototype Pattern
    • Dynamic Prototype Pattern
    • Parasitic Constructor Pattern
    • Durable Constructor Pattern
  • Inheritance

    • Prototype Chaining
    • Constructor Stealing
    • Combination Inheritance
    • Parasitic Inheritance
    • Parasitic Combination Inheritance
    • ToPrimitive(input, PreferredType?)

      1. If input is primitive, return it
      2. Depending if input is a number or string:
        • if a number first call input.valueOf() and return if primitive
        • if a string, first call input.toString() and return if primitive
      3. Call the other of input.valueOf() or input.toString() and return if primitive
      4. Throw a TypeError
    • Boolean() - Truthy/Falsy

      Falsy values - converted to false:

      • undefined, null
      • false
      • 0,NaN
      • '' (empty/zero-length string)

      All other values are converted to true.

    • Object literals

    • Dot operator

    • Bracket operator

    • Getting and setting the prototype

    • Iteration and detection of properties

    • Getting and defining properties via descriptors

    • Protecting objects

    • Methods of all objects

    • Overview

      Inheritance
      Overriding
      Sharing data between objects via a prototype
      Getting and setting the prototype
      __proto__
      Setting and deleting affects only own properties

      Iteration and Detection of Properties

      Listing own property keys
      Listing all property keys
      Checking whether a property exists

      Best Practices: Iterating over Own Properties

      Accessors (Getters and Setters)

      Defining Accessors via an Object Literal
      Defining Accessors via Property Descriptors
      Accessors and Inheritance

      Property Attributes and Property Descriptors

      Property Attributes
      Property Descriptors
      Getting and Defining Properties via Descriptors
      Copying an Object
      Properties: Definition Versus Assignment
      Inherited Read-Only Properties Can’t Be Assigned To
      Enumerability: Best Practices

      Protecting Objects

      Preventing Extensions
      Sealing
      Freezing
      Pitfall: Protection Is Shallow

    • Constructor overview

      .prototype
      .constructor
      instanceof

      The instanceof operator

      • syntax: value instanceof Constr
      • Identical to: Constr.prototype.isPrototypeOf(value)
      • Pitfall: objects that are not instances of Object
      • Pitfall: crossing realms (frames or windows)

      Tips for implementing constructors:

      • use strict mode to protect against forgetting new
      • Constructors can return arbitrary objects
    • Data in Prototype Properties

      Why you usually shouldn’t put data in prototype properties.

      Why avoid prototype properties with initial values for instance properties: mutating the value on the instance before it’s overwritten with an own property will change the prototype default value!

      Avoid nonpolymorphic prototype properties, like constants. Use variables instead.

      Polymorphic prototype properties can be used for tagging instances across realms.

    • Keeping Data Private

      JavaScript doesn’t have a built-in means for data privacy. There are three main patterns for using data privacy:

      Private data in the environment of a constructor (Crockford privacy pattern) - functions created as part of a constructor are part of that constructor’s closure. They can act as privileged methods that access data that is part of the constructor’s environment. Not very elegant, may be slower, consumes more memory, but it’s completely secure.

      Private data in properties with marked keys (private by convention) - usually with a naming convention like an underscore. This offers a more natural coding style, but it pollutes the property namespace because they’ll show up as normal properties. It can also lead to key clashes. They can be accessed normally, which can be flexible for unit tests and stuff.

      Private data in properties with reified keys - storing the key value in a variable. This avoids key clashes and lets you use UUIDs that can have unique values at runtime.

      You can keep global data private via IIFEs: attaching it to a singleton object, keeping it private to a constructor, attaching it to a method

    • Subconstructor Howto

      For two constructors Super and Sub we want:

      • Inheriting instance properties.
      • Inheriting prototype properties.
      • instanceof to work for instances
      • Overridding of methods
      • Being able to call an original from an overridden method
    • Object.prototype methods

      Conversion to Primitive

      Object.prototype.toString()
      Object.prototype.valueOf()
      Object.prototype.toLocaleString()

      Prototypal Inheritance and Properties

      Object.prototype.isPrototypeOf(obj)
      Object.prototype.hasOwnProperty(key)
      Object.prototype.propertyIsEnumerable(propKey)
    • Generic Methods

    • Pitfalls: Using an Object as a Map

      Pitfall 1: Inheritance Affects Reading Properties
      Pitfall 2: Overriding Affects Invoking Methods
      Pitfall 3: The Special Property proto

      Creating an object without a prototype (Object.create(null)) avoids all of these pitfalls.

    • Array Syntax

      var arr = ['a', 'b', 'c'];
      arr.length;
      arr.length = 2;
      arr[arr.length] = 'd';
      arr.push('e');
      var e = arr.pop();
    • Arrays are Maps, Not Tuples

      The Array type is an object with properties that have integer indices as names.

      The elements of an Array are not necessarily contiguous, and Arrays can have “holes”, or missing indices.

    • Arrays Can Also Have Properties

      Arrays work like any other object. You can add arbitrary properties to them. These new properties are not considered array elements by array methods.

    • Array Literals/Array Constructor

      // Array literal
      var arr = ['a', 'b', 'c']

      Array Constructor

      Why the Array( ) constructor is problematic:

      Creating an empty array with a given length

      // creates an array object with length 2
      var arr = new Array(2);
      // elements at indices are still undefined

      Initializing an array with elements via constructor
      Array( ) will try to parse a numeric argument as a length

      // Array with two holes, not [2]
      var arr = new Array(2);
      // RangeError: Invalid array length
      arr = new Array(9.9);
    • Multidimensional Arrays

      Create multidimensional arrays by nesting arrays. Make sure to create the rows (outer arrays). You have to do this with a loop (since a constructor will just set the length of the outer array)

    • The in Operator and Indices

    • Deleting Array Elements

      delete works on array elements but doesn’t update length or shift elements. It creates a hole.

      To delete elements without leaving a hole, use Array.prototype.splice()

      // remove i
      arr.splice(i, 1);
      // remove j through k
      arr.splice(j,k-j+1);
      // remove m up to but not including n
      arr.splice(m, n-m);
      // remove the third last element and after
      arr.splice(-3);
    • Array Indices in Detail

      Indices aren’t numbers, but string property keys.

      For a key P that is a valid array index:

      • ToString(ToUint32(P)) === P is true
      • ToUint32(P) !== Math.pow(2,32)-1
    • Manually Increasing the Length of an Array

      Changing length only creates holes (doesn’t create new, empty array elements).

    • Decreasing the Length of an Array

      This does actually delete elements (trying to access afterwards will return undefined)

      You can clear an array by setting length to 0. This clears the array for all variables accessing the object. But this operation can be slow and it is easier to create a new, empty array.

    • Creating Holes / Sparse Arrays

      You can create holes by omitting values in literals and assigning to nonconsecutive indices.

      Trying to access a hole returns undefined. Unlike an actual undefined at that index, it’s not detected by the in operator. Array iteration methods also ignore them.

    • Which Operations Ignore Holes, and Which Consider Them?

      Array iteration methods

      Method Behavior
      forEach() ignores
      every() ignores
      map() skips but preserves
      filter() eliminates
      Method Behavior
      join() converts holes, undefined, null to ''
      sort() preserves while sorting

      Function.prototype.apply()

      When apply() accepts an otherwise empty array with holes, it turns them to undefined.

      You can create an array with undefined as values with Array.apply. But apply wont’ necessarily replace holes with undefined in nonempty arrays.

    • Removing Holes from Arrays

      filter( ) removes holes.

      To replace holes with undefined, use a loop that assigns each array element to itself.

    • Comparing Numbers

    • Examination Methods

      Array.prototype.forEach(callback, thisValue?) - iterates over all elements. Doesn’t support break—use some( ) instead

      Array.prototype.every(callback, thisValue?) - true if true for every element; stops as soon as it gets false

      Array.prototype.some(callback, thisValue?) - returns true if the callback returns true for at least one element. Stops iteration once it gets a true

    • Transformation Methods

      function callback(element, index, array)

      Array.prototype.map(callback, thisValue?) - return an array with callback applied to each element

      Array.prototype.filter(callback, thisValue?) - return a new array containing only elements for which callback returned true

    • Reduction Methods

      function callback(previousValue,
       currentElement, currentIndex, array)

      Array.prototype.reduce(callback, initialValue?)
      Array.prototype.reduceRight(callback, initialValue?)

      If initial value is not provided, previousValue is the first element and currentElement is the second element.

    • Undefined type

      • Superficially equal to null
    • Null type

      • Superficially equal to undefined
    • Number

      Integers (dec, octal, hex)

      55
      070
      0xA

      Floating Point (IEEE 754)

      301.001
      2.91E23

      Range: Number.MIN_VALUE Number.MAX_VALUE

      Infinity -Infinity - can’t be used in further calculations. Check with isFinite( ).

      NaN - detect with isNaN( )

      Cast to number type with Number( )

    • String

      Characters, character strings, character literals.

      • Can be enclosed in single '' or double "" quotes.
      • Character literals (\n\t\\, unicode, etc) are counted as single characters, not by the number of characters in their ascii escape sequence.
      • Are immutable.
      • Other types can be type cast using toString( )
    • Object

      _JavaScript objects

      All objects have the following methods:

      • hasOwnProperty( prop )
      • isPrototypeOf( obj )
      • propertyISEnumerable( prop )
      • toLocaleString() - return string representation of object that is appropriate for locale
      • toString() - string representation of object
      • valueOf() - string, number, or Boolean representation of object
    • Unary + -

      • + does nothing to a number type variable, casts the variable using Number()
      • - negates a number type variable, and returns the negation of a non-numeric value after its converstion with Number()
    • Logical ! && ||

      Operand !
      true false
      false true
      object false
      empty string true
      nonempty string false
      0 true
      nonzero number false
      null true
      NaN true
      `undefined true

      && will always short circuit to false if the first operand is false.

      || will always short circuit to true if the first argument is true

      Operand1 Operand2 && OR
      true true true true
      true false false true
      false * short circuit false Operand2
      true false false short circuit true
      Object * Operand2 Operand1
      true Object Operand2 short circuit true
      Object Object Operand2 Operand1
      null * null null if Operand2===null
      NaN * NaN NaN if Operand2===NaN
      undefined * undefined undefined if Operand2===undefined
      undeclared * error error
      true undeclared error short circuit true
      false undeclared short circuit false error
    • Comma

      Allows execution of more than one operation in a single statement.

      Usually used for variable declaration.

      var a1=1,
        a2=2,
        a3=3;

      When used to assign values, returns the last item in the expression.

      var num = (5, 1, 4, 8, 0); // num = 0
    • Labeled statements

      butts: for (var i=0; i < count; i++) {
         console.log(i*i);
      }
    • break and continue

      break exits a loop immediately, and the next statement after the loop is executed.

      continue exits a loop iteration, but execution resumes the beginning of the loop.

      You can specify a labeled statement as the target of break or continue. This is powerful but can cause debugging problems.

    • with

      Not allowed in strict mode. Don’t use in production code.

      var qs = location.search.substring(1);
      var hostName = location.hostname;
      var url = location.href;

      is equivalent to:

      with(location){
        var qs = search.substring(1);
        var hostName = hostname;
        var url = href;
      }
    • switch

      Matches similar to ==. Works with all data types, including strings and objects. Case values do not need to be constants.

    • Dynamic Properties

    • Copying Values

    • Activation Object of a Function

      Starts with arguments.

      Next variable object is from the containing context.

      Each subsequent variable object in the chain is that of the next immediately enclosing scope.

      The last variable object in the chain belongs to the global scope.

    • Scope Chain Augmentation

      A catch block in a *try-catch statement and a with statement both add a variable object to the front of a scope chain.

      with

      with (aThing) {
        /* ... */
      }

      aThing is added to the scope chain.

      try-catch

      try {
      } catch (e) {
         /* ... */
      }

      The catch statement will create a new variable object containing e, the error object that was thrown.

    • No-Block Level Scoping

      Variables declared in blocks, such as in if statements and in the initialization part of for statements are available in the rest of the enclosing function scope.

    • Variable Declaration

      Declaring a variable with var will add it to the immediate context.

      ! - A variable that gets initialized without being declared gets added to the global context: it will continue to exist until execution exits the global scope.

      Always declare variables before initializing this to avoid problems.

    • Resolving Identifiers

      Identifiers get resolved by navigating the scope chain from beginning to end.

      A variable is accessible as long as it can be found in the scope chain.

      The search may also search each object’s prototype chain.

      The first match in the identifier search gets returned.

      var name = "Khyr ad-Din";
      function getName() {
        var name = "Edmund Harvey";
        return name;
      }
      console.log(getName()); // "Edmund Harvey"

      In this case the name variable in the parent context of getName can’t be accessed.

    • Reference Counting

      Cyclic References Example

      function thing() {
        var objA = new Object();
        var objB = new Object();
      
        objA.friend = objB;
        objB.friend = objA;
      }

      Even once browsers switched to mark-and-sweep GC, non-native JavaScript objects (COM, DOM, BOM) in IE8 and earlier were still vulnerable to cyclic references because they were still implemented with reference counting.

      ! - Make sure to break the connection between native JS and DOM elements by setting cross-references to null.

    • Performance Issues

      IE6 and earlier ran GC when threshold of 256 variable allocations, 4096 object/array literals/array slots, or 64kb of strings was reached.

      Scripts with a lot of variables/strings kept the GC running really frequency, leading to performance issues.

      IE7 instead had dynamic thresholds based on how many allocations were reclaimed per sweep.

    • Creating Arrays, best practices

      There are two main ways to create an array:

      1. Array constructor

      2. Array literal

      var anEmptyArray = []; // creates an empty array
      var numbersAgain = [1,2,]; // don't do this
      var numbersOrWhat = [,,,,,] // don't do this either

      Creating empty arrays with commas, or leaving the last element blank causes inconsistent behavior. In IE8 and earlier, the last, hanging comma will create an additional index with the value undefined (this is a bug). Other browsers will not create an additional index giving a hanging comma.

      Array literal notation doesn’t call the Array() constructor except in Firefox 2.x and earlier.

    • Detecting Arrays

      x instanceof Array will not correctly identify x as an Array if it was passed from a different frame or page, and x‘s array type has a different constructor.

      Instead, ECMAScript 5 provides Array.isArray( anObject ) to detect arrays.

    • Conversion Methods

      .toString() .valueOf()

      Returns a comma delimited list of each element’s .toString() values.

      .toLocaleString()

      Returns a comma delimited list of each element’s .toLocaleString() values.

      .join(sep)

      Returns a list separated by the string specified by sep.

      If sep is not provided or undefined, it uses a comma. IE 7 and before has a bug that uses undefined as the delimiter.

    • Stack Methods

      push(itemTachi, ...)

      Appends any number of elements to the end of an array.

      pop()

      Returns the last element of the array and decrements the length property.

    • Queue Methods

      shift()

      Returns the first element of the array removes it from the array (shifting all the indicies downward).

      unshift(elemTachi, ...)

      Prepends any number of elements to an array.

    • Reordering Methods

      .reverse() - reverses the elements in the array.

      .sort( comparator )

      Sorts the elements of the array based on a comparison function. For each pair of elements in an array, the comparison function should basically do this:

      function comparator(v1, v2) {
        if ( /* v1 < v2 */) {
          return -1;
        } else if (/* v1 > v2 */) {
          return 1;
        } else {
          return 0;
        }
      }

      If no comparison function is provided, sort() will return the elements in sorted in ascending order of their String() values by default.

    • Manipulation Methods

      .concat( elementsOrArraysTachi, ... )

      Returns a new array with specified elements appended to the end of the original array. Will append the elements of any arrays passed into it. If no elements or arrays are passed in, it will clone the original array.

      .slice( startIndex, stopIndex )

      Returns a new array containing elements between startIndex and up to but not including stopIndex. stopIndex is optional and if it is not specified, slice( ) will just return elements from startIndex up to the end of the array.

      .splice(startIndex, replaceCount, elem[,...] )

      Splice can delete, insert, or replace items in the middle (or at any point) of an array.

      Deletion - specify two arguments: startIndex is the first item to delete, and replaceCount is the number elements to delete.

      Insertion - specify three or more arguments: startIndex is the insertion point, have replaceCount=0, and then specify any number of elements to insert.

      Replacement - specify three or more arguments: startIndex is the replacement point, replaceCount is the number of elements to delete, and elem[…] are the items to insert.

    • Location Methods

      Each of these uses the === operator to find a match:

      .indexOf()

      .lastIndexOf()

    • Iterative Methods

      Let f( ) be a function that takes the following arguments (all optional):

      function f(elem, i, array)

      Each of the following methods run f( ) for each element in the array. The current element is passed as elem, the index as i, and the array itself as array.

      Method return value
      .every(f) true if f( ) returns true for every element in the array, false otherwise
      .filter(f) array of all items for which f( ) returns true
      .forEach(f) no return value
      .map(f) result of each call to f( ), as an array
      .some(f) true if f( ) returns true for any item
    • Reduction Methods

      .reduce(f, iv) .reduceRight(f, iv)

      Iterates through all elements of an array, either from the first element (reduce) or from the last element reduceRight.

      function f(prev, cur, index, theArray) {
        /* ... */
        return val;
      }

      iv (optional) is passed in as prev on the first iteration (when cur is set to element 0).

      The return value of the function (val in f) is passed in as prev on the next iteration.

      e.g. sequences, series, iterative algorithms

    • Function Declarations versus Function Expressions

      Function Declarations are available in an execution context before any code is executed. This is called function declaration hoisting. The engine takes any Javascript function it finds and brings it to the top of the source tree.

      Function Expressions aren’t available until the line of code (usually assigning a function to a variable) gets executed. If a function gets called before it’s assigned in a function expression, it will cause an “unidentified identifier” error.

    • Functions as Values

      Functions can be used any place any other value can be used.

      It’s possible to:

      • Pass a function into another function
      • Return a function as a result of another function

      This is important—you can use this to create a comparison function to use with sort() that knows what properties of objects to compare.

    • Function Internals

      A function contains three special objects:

      arguments - Contains arguments passed to the function and a property callee which is a pointer to the function that owns the arguments object. This can be important for decoupling arguments from the function’s label, such as in recursive functions.

      • Strict mode: trying to access arguments.callee results in an error.
      • ECMAScript 5 also has arguments.caller. Accessing arguments.caller in strict mode causes an error.

      Example: write a recursive function (recursive merge sort, factorial) that still works even the name of the function gets changed.

      this - a reference to the context object the function is operating on. The value of this is not determined until the function is called. It is set to the global context by default.

      • Strict mode: when a function is called without a context object, this is set to undefined unless apply() or call() are used.

      Example: write a function that uses this to produce different output depending on the object that is the context (e.g. window vs. an object).

      caller - (ECMAScript 5) contains a reference to the calling function, or null if the function was called in the global scope.

      • Strict mode: trying to assign a value to caller causes an error.
    • Function Properties and Methods

      Properties

      length - the number of named arguments that the function expects

      prototype - prototype for reference types. Not enumerable in ECMAScript 5.

      Methods

      apply(valueOfThis, argsArray) call(valueOfThis, arg1[,...] )

      Execute the function with a particular this context. apply accepts an array of arguments (either an Array type or the arguments object) and call accepts any number of arguments directly.

      window.color = "red";
      var o = { color: "blue" };
      
      function sayColor() {
        console.log(this.color);
      }
      
      sayColor(); // red
      sayColor.call(this); // red
      sayColor.call(window); // red
      sayColor.call(o); // blue

      bind(thisValue) (ECMAScript 5)

      Creates a new function object instance with the this value set to the specified value.

      window.color = "Aquamarine";
      var o = { color: "CornflowerBlue" };
      
      function sayColor() {
        console.log(this.color);
      }
      var objectSayColor = sayColor.bind(o);
      objectSayColor(); // CornflowerBlue

      toString() toLocaleString()

      Returns the function’s code.

    • The Boolean Wrapper Type

      valueOf() - Returns true or false

      toString() toLocaleString() - Returns 'true' or 'false' (string values)

      Don’t use Boolean types in boolean expressions! They are treated and evaluated as objects.

    • The Number Wrapper Type

      valueOf() - Returns the primitive numeric value.

      toString() toLocaleString() - Return the string representation of the numeric value.

      toFixed(places) - string representation of a number with a specified number of decimal points, rounded.

      Rounding is bugged in IE 8 and earlier: it rounds numbers in (-0.94,-0.5] [0.5,0.94) when precision is 0. It will round numbers in these ranges to 0 when they should be rounded to 1 or -1.

      toExponential(places) - string representation in e-notation.

      var num = 10;
      console.log(num.toExponential(1)); // '1.0e+1'

      toPrecision(precision) - returns string representation of number in either fixed or exponential notation with precision number of digits, rounding when appropriate. Can typically represent numbers with 1 through 21 decimal places.

    • The String Wrapper Type

      String Character Methods

      charAt(i) - returns character at position in string

      charCodeAt(i) - returns character code at position in string

      ECMAScript 5 allows bracket notation.

      var s = "My Butt";
      console.log(s[3]); // 'B'

      String-Manipulation Methods

      concat( ) - return concatenation of one or more strings

      slice(startPos, stopPos)

      • Negative arguments treated as length+arg.

      substring(startPos, stopPos)

      • Negative arguments converted to 0.

      substr(startPos, count)

      • Negative startPos treated as length+arg.
      • Negative count converted to 0.

      String Location Methods

      indexOf(s)
      lastIndexOf(s)

      The trim() Method

      trim() - Returns a copy of a string with leading and trailing white space removed.

      trimLeft() trimRight() - Nonstandard methods supported in Firefox 3.5+, Safari 5+, Chrome 8+.

      String Case Methods
      toLowerCase() toLocaleLowerCase()
      toUpperCase() toLocaleUpperCase()

      String Pattern Matching Methods
      match( regEx ) - returns an array where the first element is the string that matches the entire pattern, and then capturing groups

      search( regEx ) - returns index of substring matching regular expression or -1 if not found

      replace( searchText, r ) - matches based on a regular expression or a string. r can be string or a function. If r is a string, it supports special codes for replacement text. If r is a function, it gets passed three arguments: the string match, the position of the match, and the whole string. Additional capturing groups can get passed in as an argument. The only way to replace all occurrences is to pass in a RegEx type with the g flag set.

      • When r is a string, you can insert regular expression operation values. (See table).

      split(sep, arrayLimit) - separates a string into an array of substrings based on separator sep, which may be a string or RegEx

      • Capturing group behavior differs widely across browsers
      • IE8 and earlier ignore capturing groups
      • Firefox 3.6 includes empty strings in the results array when a capturing group has no match

      localeCompare(s) - comparator method that returns different values based on whether a string comes before another alphabetically (return values vary slightly by implementation)

      • before s: negative number (usually -1)
      • equal to s: 0
      • after s: positive number (usually 1)

      String.fromCharCode( num[,...], ) - creates a string from character codes

    • Global object

      Properties
      undefined NaN Infinity Object Array Function Boolean String Number Date RegExp Error EvalError RangeError ReferenceError SyntaxError TypeError URIError

      Window Object

      In browsers, the window object acts as the global object’t delegate, and it gets all the variables and functions declared in the global scope.

    • URI-Encoding Methods

      encodeURI(s) - encodes a string into a valid URI. Meant to be used on an entire URI, so does not encode valid URI components, such as colons, forward slashes, question marks, and percent signs.

      encodeURIComponent(s) - encodes all nonstandard characters

      decodeURI(s) - decodes the characters of a URI into a string. Only decodes characters that would have been replaced by encodeURI()

      decodeURIComponents(s) - decodes a URI into a string

    • The eval() method

      • Strict Mode: variables and functions created in eval are not accessible outside.
    • Math Object

      Properties (constants)

      Math.E
      MathLN10
      Math.LN2
      Math.LOG2E - base 2 log of e
      Math.LOG10E - base 10 log of e
      Math.PI
      Math.SQRT1_2 - square root of 1/2
      Math.SQRT2

      Methods

      Math.min(x1[, ...] ) - returns the smallest number in a group of numbers. Accepts any number of parameters.

      Math.max(x1[, ...] ) - returns the largest number in a group of numbers.

      Math.ceil(x) - ceiling function

      Math.floor(x) - floor function

      Math.round(x) - rounds number up if decimal component is >= 0.5, or down if not.

      Math.random() - generates a random number in (0,1)

      Other methods:

      Math.abs(x)
      Math.exp(x) - e^x
      Math.log(x)
      Math.pow(x, t) - x^tMath.sqrt(x)`Math.acos(x) - arc cosine of x
      Math.asin(x) - arc sine of x
      Math.atan(x) - arc tan of x
      Math.atan2(y,x) - arc tangent of y/x
      Math.cos(x) - cosine x
      Math.sin(x) - sine x
      Math.tan(x) - tan x

      The precision of results may vary from implementation to implementation.

    • Types of Properties

      Data properties and Accessor properties are the two types of properties in JavaScript.

      Data Properties - single location for a data value

      Accessor Properties - combination of getter/setter functions

    • What the new operator actually does

    • constructor property of instances

      Use cases for the constructor property:

      • Identifying/taking different action on an object based on its constructor (only works on direct instances of a constructor)
      • Determining the name of an object’s constructor with .constructor.name. (Not all JS engines support function property name.)
      • Creating a new object with the same constructor
      • Referring to a superconstructor

      Best practice: make sure that for a constructor C, C.prototype.constructor === C is true. Functions have this set up correctly by default. Avoid replacing the prototype object, and if you do, manually assign the right value to constructor.

    • The instanceof operator

      value instanceof Constr

      Checks the whole prototype chain. Always returns false for primitive operands. Throws an exception if rhs operand isn’t a function.

      Identical to:

      Constr.prototype.isPrototypeOf(value)

      Pitfall: objects that aren’t instances of Object don’t get identified as an object by instanceof.

      Pitfall: instanceof might not work across different frames and windows, which each have their own global variables.

      Workarounds:

      • Use special methods like Array.isArray()
      • Avoid crossing realms (windows/frames) by using postMessage( ) to copy over objects
      • Compare the .constructor.name
      • Use a property on the prototype to mark instances
    • Tips for implementing constuctors

      Use strict mode to protect against forgetting to use new. Strict mode will raise an exception:

      TypeError: Cannot set property 'name' of undefined

      Returning arbitrary objects from a constructor. JavaScript can return arbitrary objects, allowing you to use them as factory methods.

      function Expression(str) {
          if (...) {
              return new Addition(..);
          } else if (...) {
              return new Multiplication(...);
          } else {
              throw new ExpressionException(...);
          }
      }
      ...
      var expr = new Expression(someStr);
    • Avoid prototype properties with initial values

      Do this instead to create a new property on the instance with a default value:

      function Names(data) {
          this.data = data || [];
      }

      When you might use prototype property with an initial value:

      Lazy instantiation of properties

      function Names(data) {
          if (data) this.data = data;
      }
      Names.prototype = {
          constructor: Names, // (1)
          get data() {
              // Define, don’t assign
              // => avoid calling the (nonexistent) setter
              Object.defineProperty(this, 'data', {
                  value: [],
                  enumerable: true,
                  configurable: false,
                  writable: false
              });
              return this.data;
          }
      };
    • Private Data in the Environment of a Constructor (Crockford Privacy Pattern)

      Public properties

      Constr.prototype.publicMethod = ...;
      function Constr(...) {
          this.publicData = ...;
          ...
      }

      Private values

      function Constr(...) {
          ...
          var that = this; // make accessible to private functions
      
          var privateData = ...;
      
          function privateFunction(...) {
              // Access everything
              privateData = ...;
      
              that.publicData = ...;
              that.publicMethod(...);
          }
          ...
      }

      Privileged methods

      function Constr(...) {
          ...
          this.privilegedMethod = function (...) {
              // Access everything
              privateData = ...;
              privateFunction(...);
      
              this.publicData = ...;
              this.publicMethod(...);
          };
      }
    • Private Data in Properties with Reified Keys

      var StringBuilder = function () {
          var KEY_BUFFER = '_StringBuilder_buffer';
      
          function StringBuilder() {
              this[KEY_BUFFER] = [];
          }
          StringBuilder.prototype = {
              constructor: StringBuilder,
              add: function (str) {
                  this[KEY_BUFFER].push(str);
              },
              toString: function () {
                  return this[KEY_BUFFER].join('');
              }
          };
          return StringBuilder;
      }();

      Note the IIFE.

    • Keeping Global Data Private via IIFEs

      Attaching private global data to a singleton object

      var obj = function () {  // open IIFE
      
          // public
          var self = {
              publicMethod: function (...) {
                  privateData = ...;
                  privateFunction(...);
              },
              publicData: ...
          };
      
          // private
          var privateData = ...;
          function privateFunction(...) {
              privateData = ...;
              self.publicData = ...;
              self.publicMethod(...);
          }
      
          return self;
      }(); // close IIFE

      Keeping global data private to all of a constructor

      var StringBuilder = function () { // open IIFE
          var KEY_BUFFER = '_StringBuilder_buffer_' + uuid.v4();
      
          function StringBuilder() {
              this[KEY_BUFFER] = [];
          }
          StringBuilder.prototype = {
              // Omitted: methods accessing this[KEY_BUFFER]
          };
          return StringBuilder;
      }(); // close IIFE

      Attaching global data to a method

      var obj = {
          method: function () {  // open IIFE
      
              // method-private data
              var invocCount = 0;
      
              return function () {
                  invocCount++;
                  console.log('Invocation #'+invocCount);
                  return 'result';
              };
          }()  // close IIFE
      };
    • Utility function

      function subclasses(SubC, SuperC) {
          var subProto = Object.create(SuperC.prototype);
          // Save `constructor` and, possibly, other methods
          copyOwnPropertiesFrom(subProto, SubC.prototype);
          SubC.prototype = subProto;
          SubC._super = SuperC.prototype;
      };
    • Inheriting Instance Properties

      function Sub(prop1, prop2, prop3, prop4) {
          Sub._super.call(this, prop1, prop2);  // (1)
          this.prop3 = prop3;  // (2)
          this.prop4 = prop4;  // (3)
      }

      The trick is to not invoke Super via new.

    • Inheriting Prototype Properties / making instanceof work for instances

      Give sub.prototype the prototype super.prototype.

      Sub.prototype = Object.create(Sub._super.prototype);
      Sub.prototype.constructor = Sub;
      Sub.prototype.methodB = ...;
      Sub.prototype.methodC = ...;
    • Overriding a Method vs. Making a Supercall

      Methods added to Sub.prototype will override methods with the same name in Super.prototype.

      A home object of a method is the object that owns the property that contains the method.

      To call a supermethod, skip the home object of the current method, search for a method with that name, and invoke with the current this.

      Sub.prototype.methodB = function (x, y) {
          var superResult = Sub._super.prototype.methodB.call(this, x, y); // (1)
          return this.prop3 + ' ' + superResult;
      }
    • Example

      Superconstructor

      function Person(name) {
          this.name = name;
      }
      Person.prototype.describe = function () {
          return 'Person called '+this.name;
      };

      Subconstructor

      function Employee(name, title) {
          Person.call(this, name);
          this.title = title;
      }
      Employee.prototype = Object.create(Person.prototype);
      Employee.prototype.constructor = Employee;
      Employee.prototype.describe = function () {
          return Person.prototype.describe.call(this)+' ('+this.title+')';
      };
    • Accessing Object.prototype and Array.prototype via Literals

      Just use the empty object {} instead of Object.prototype and [] instead of Array.prototype.

    • Examples

      > var arr1 = [ 'a', 'b' ];
      > var arr2 = [ 'c', 'd' ];
      
      > [].push.apply(arr1, arr2)
      4
      > arr1
      [ 'a', 'b', 'c', 'd' ]
      > Array.prototype.join.call('abc', '-')
      'a-b-c'
      > [].map.call('abc', function (x) { return x.toUpperCase() })
      [ 'A', 'B', 'C' ]
      > 'abc'.split('').map(function (x) { return x.toUpperCase() })
      [ 'A', 'B', 'C' ]
      > String.prototype.toUpperCase.call(true)
      'TRUE'
      > String.prototype.toUpperCase.call(['a','b','c'])
      'A,B,C'
      > var fakeArray = { 0: 'a', 1: 'b', length: 2 };
      > Array.prototype.join.call(fakeArray, '-')
      'a-b'
      > var obj = {};
      > Array.prototype.push.call(obj, 'hello');
      1
      > obj
      { '0': 'hello', length: 1 }
      function logArgs() {
          Array.prototype.forEach.call(arguments, function (elem, i) {
              console.log(i+'. '+elem);
          });
      }
    • Array-Like Objects and Generic Methods

      arguments
      DOM node lists - returned by document.getElementsBy*()
      Strings

      Array-like objects need elements accessible by integer indices and a length property. Array methods need these to be readable, and sometimes writable.

    • isNaN( x )

      • false if value can be converted into a number
      • true if it cannot

      When applied to objects, calls valueOf( ) method.

    • Number( x )

      Input Output
      Boolean true->1; false->0
      Number (passes through)
      null 0
      undefined NaN

      Strings

      String Output
      numeric strings, no decimal decimal integer
      floating point format floating point
      hex format hex
      empty 0
      anything else NaN
    • parseInt( x, radix )

      Returns the first contiguous numeral string’s numerical value, ignoring the rest of the string.

    • parseFloat( x )

      Will return the value of the the first valid contiguous numerical string in floating point format.

    • Trivia: bind(con) will keep the new function bound to con even when you attempt to use apply or call with a different context!

    • String Type Trivia

      • concat( ) will convert any non-string type into a string. For example, an Array ['a', 'b'] will be converted to 'a,b'
    • replace( ) character sequences

      Sequence Replacement Text
      $$ $
      $& Substring matching entire pattern
      $' Right context
      $` Left context
      $n n th capture (0-9)
      $nn nn th capture (01-99)
    • Data Properties

      Attributes

      [[Configurable]]
      [[Enumerable]]
      [[Writable]]
      [[Value]]

    {"cards":[{"_id":"6233fff7781cf6071600010f","treeId":"6233ffe7781cf6071600010d","seq":5897645,"position":1,"parentId":null,"content":"# Programming Languages"},{"_id":"62340052781cf60716000110","treeId":"6233ffe7781cf6071600010d","seq":5897651,"position":2,"parentId":null,"content":"## Python\n\nPython is a strongly-typed, dynamically typed multi-paradigm language created by Guido Van Rossum."},{"_id":"62340328781cf60716000111","treeId":"6233ffe7781cf6071600010d","seq":5897735,"position":1,"parentId":"62340052781cf60716000110","content":"### Functions\n\nFunctions look like this:\n\n```\ndef aFunction(params):\n print \"Do something\"\n return 1\n```\n\nAll functions return a value.\n"},{"_id":"62342ce4781cf60716000118","treeId":"6233ffe7781cf6071600010d","seq":5897869,"position":1,"parentId":"62340328781cf60716000111","content":"#### Built-In Functions\n\n`type( )` - returns datatype of an object. Possible types are listed in the `types` module.\n\n`str( )` - coerces data into a string\nGotchas: string representation of modules includes the pathname of the module on disk.\n\n`dir( )` - returns list of attributes and methods of any object\n\n`callable( )` - returns `True` if object is callable as a function, `False` if not. Functions, methods, and classes count as callable.\n\n`getattr(object, callablename, defaultvalue)` - returns a reference to a function or method. Works on functions and methods from modules, and on lists and dicts, but not tuples (which have no methods)."},{"_id":"62342094781cf60716000116","treeId":"6233ffe7781cf6071600010d","seq":5897741,"position":1.5,"parentId":"62340052781cf60716000110","content":"### Code Blocks/Indentation\n\nCode blocks are denoted by indentation. [PEP8](https://www.python.org/dev/peps/pep-0008/#indentation) specifies that indents should be 4 spaces."},{"_id":"623406f4781cf60716000112","treeId":"6233ffe7781cf6071600010d","seq":5897664,"position":2,"parentId":"62340052781cf60716000110","content":"### Objects\n\nEverything, including functions, are objects in Python."},{"_id":"6234128b781cf60716000114","treeId":"6233ffe7781cf6071600010d","seq":5897750,"position":1,"parentId":"623406f4781cf60716000112","content":"#### Doc Strings\n\nA function's doc strings are accessible as `str` types via the `__doc__` attribute.\n\n```\nprint aFunction.__doc__\n```"},{"_id":"623410a3781cf60716000113","treeId":"6233ffe7781cf6071600010d","seq":5897751,"position":2,"parentId":"623406f4781cf60716000112","content":"#### Search Path\n\nThe library search path is defined in `sys.path` as a list."},{"_id":"623423ac781cf60716000117","treeId":"6233ffe7781cf6071600010d","seq":5897775,"position":3,"parentId":"623406f4781cf60716000112","content":"#### Modules\n\nYou can get the module name with the `__name__` attribute. This is commonly used to check if the current script is running as a standalone program:\n\n```\nif __name__ == \"__main__\"\n```\n\nThis is good to use for writing/running test suites for a class or script."},{"_id":"62345c02781cf6071600011a","treeId":"6233ffe7781cf6071600010d","seq":5897958,"position":3,"parentId":"62340052781cf60716000110","content":"### List Comprehensions\n\n```\n[aFunction(elem) for elem in aList]\n```\n\nWill return a new list:\n> \"It is safe to assign the result of a list comprehension to the variable that you're mapping. Python constructs the new list in memory, and when the list comprehension is complete, it assigns the result to the variable.\""},{"_id":"623478b5781cf6071600011d","treeId":"6233ffe7781cf6071600010d","seq":5897964,"position":3.5,"parentId":"62340052781cf60716000110","content":"### String Methods\n\n`.lower( )`\n\n`.upper( )`\n\n`.join(aList )` - join any list of strings into a single string. Handy when used in conjunction with list comprehensions.\n\n`.split(aDelimiter, timesToSplit)` - splits a string into a list given a delimeter"},{"_id":"623471af781cf6071600011c","treeId":"6233ffe7781cf6071600010d","seq":5897927,"position":4,"parentId":"62340052781cf60716000110","content":"### Dicts\n\n`keys()` - returns list of all keys (in a particular order, but not necessarily order of definition)\n`values()` - returns list of all values: same order as `keys()`\n`items()` - returns a list of tuples of the form (key,value)"},{"_id":"625beef671800f9971000033","treeId":"6233ffe7781cf6071600010d","seq":6294728,"position":3,"parentId":null,"content":"## JavaScript\n\nJavascript is a dynamic, untyped, object-oriented prototypal language created by Brendan Eich."},{"_id":"6582d65150ac877b45000086","treeId":"6233ffe7781cf6071600010d","seq":6573874,"position":0.25,"parentId":"625beef671800f9971000033","content":"# Speaking JavaScript"},{"_id":"6582cc1050ac877b45000085","treeId":"6233ffe7781cf6071600010d","seq":6562358,"position":1,"parentId":"6582d65150ac877b45000086","content":"### 3. The Nature of JavaScript\n\nDynamic.\nDynamically typed.\nFunctional and object oriented.\nFails silently.\nDeployed as source code.\nPart of the web platform.\n\nQuirks\n\nNo block-scoped variables\nNo built-in modules\nNo support for subclassing\nNo integers (engines optimize this)\nArrays too flexible (engines optimize this)\n\nElegant Parts\n\nFirst class functions\nClosures\nPrototypes\nObject literals\nArray literals\n\nInfluences\n\nJava - syntax\nAWK - functions\nScheme - first-class functions and closures\nSelf - prototypal inheritance\nPerl/Python - strings, arrays, regex\nHyperTalk - integration into web browsers, event handling attributes in HTML"},{"_id":"6582d94a50ac877b45000087","treeId":"6233ffe7781cf6071600010d","seq":6562372,"position":2,"parentId":"6582d65150ac877b45000086","content":"Netscape originally hired Brandan Eich to implement Scheme in the browser. But then Netscape partnered with Sun to bring Java to the browser. Because of that, JavaScript needed to have syntax similar to Java.\n\nJavaScript's first name was Mocha. It was renamed to LiveScript before the final name, JavaScript was adopted."},{"_id":"658d2df150ac877b45000088","treeId":"6233ffe7781cf6071600010d","seq":6573891,"position":3,"parentId":"6582d65150ac877b45000086","content":"## 7.JavaScript's Syntax\n\nBasic expressions and statements\nComments\nExpressions versus statements\nControl flow statements and blocks\nRules for using semicolons\nLegal identifiers\nInvoking methods on number literals\nStrict mode"},{"_id":"658d429550ac877b45000090","treeId":"6233ffe7781cf6071600010d","seq":6573892,"position":0.0078125,"parentId":"658d2df150ac877b45000088","content":"### Basic expressions and statements"},{"_id":"658d426850ac877b4500008f","treeId":"6233ffe7781cf6071600010d","seq":6573888,"position":0.015625,"parentId":"658d2df150ac877b45000088","content":"### Comments"},{"_id":"658d421650ac877b4500008e","treeId":"6233ffe7781cf6071600010d","seq":6573887,"position":0.03125,"parentId":"658d2df150ac877b45000088","content":"### Expressions versus statements"},{"_id":"658d41c150ac877b4500008d","treeId":"6233ffe7781cf6071600010d","seq":6573886,"position":0.0625,"parentId":"658d2df150ac877b45000088","content":"### Control flow statements and blocks"},{"_id":"658d417c50ac877b4500008c","treeId":"6233ffe7781cf6071600010d","seq":6573885,"position":0.125,"parentId":"658d2df150ac877b45000088","content":"### Rules for using semicolons"},{"_id":"658d412f50ac877b4500008b","treeId":"6233ffe7781cf6071600010d","seq":6573883,"position":0.25,"parentId":"658d2df150ac877b45000088","content":"### Legal identifiers"},{"_id":"658d40aa50ac877b4500008a","treeId":"6233ffe7781cf6071600010d","seq":6573881,"position":0.5,"parentId":"658d2df150ac877b45000088","content":"### Invoking methods on number literals"},{"_id":"658d38bb50ac877b45000089","treeId":"6233ffe7781cf6071600010d","seq":6573882,"position":1,"parentId":"658d2df150ac877b45000088","content":"### Strict mode\nSwitching on strict mode\nCaveats on using strict mode\nFunctions in strict mode\nSetting and deleting immutable properties fails with an exception in strict mode\nUnqualified identifiers can't be deleted in strict mode\nFeatures that are forbidden in strict mode"},{"_id":"659a3fe450ac877b45000091","treeId":"6233ffe7781cf6071600010d","seq":6581581,"position":4,"parentId":"6582d65150ac877b45000086","content":"## 8. Values\n\nJavaScript's Type System\nPrimitive Values Versus Objects\nPrimitive Values\nObjects\nundefined and null\nWrapper Objects for Primitives\nType Coercion"},{"_id":"659a42c250ac877b45000092","treeId":"6233ffe7781cf6071600010d","seq":6581586,"position":1,"parentId":"659a3fe450ac877b45000091","content":"### JavaScript's Type System\n\nJavaScript's Types - JavaScript has six types: undefined, null, Boolean, Number, String, and Object.\n\nStatic Typing Versus Dynamic Typing/Type Checking - JavaScript is dynamically typed (types not known until runtime). It only does dynamic type checking when trying to use a property of null or undefined.\n\nCoercion - most operands convert operands to a primitive type -- Boolean, Number, String, and Object."},{"_id":"659a519250ac877b45000093","treeId":"6233ffe7781cf6071600010d","seq":6581592,"position":2,"parentId":"659a3fe450ac877b45000091","content":"### Primitive Values Versus Objects\n\nbooleans, numbers, strings, null, and undefined are primitive types. Everything else in JavaScript is an object. Objects are only strictly equal (`===`) to themselves. All primitive types are equal if they contain the same value."},{"_id":"659a53f950ac877b45000094","treeId":"6233ffe7781cf6071600010d","seq":6581598,"position":3,"parentId":"659a3fe450ac877b45000091","content":"### Primitive Values\n\nBooleans: true, false\nNumbers: IEEE-754 floating point, 64-but\nStrings: Unicode characters surrounded by quotes\nUndefined: `undefined`\nNull: `null` (`typeof` returns `Object`)\n\nPrimitives are compared by value and are immutable. You cannot define new primitive types."},{"_id":"659a583f50ac877b45000095","treeId":"6233ffe7781cf6071600010d","seq":6581601,"position":4,"parentId":"659a3fe450ac877b45000091","content":"### Objects\n\nAll nonprimitive values are Objects. The most common kinds of objects are plain objects, arrays, and regular expressions.\n\nObjects are compared by reference, mutable by default, and extensible by the user."},{"_id":"659a5e6950ac877b45000096","treeId":"6233ffe7781cf6071600010d","seq":6581613,"position":5,"parentId":"659a3fe450ac877b45000091","content":"### undefined and null\n\n`undefined` means no value, and uninitialized variables, missing parameters/properties have this value. Functions return `undefined` by default.\n\n`null` means no object. It is the last element in the prototype chain and gets returns if there is no match for a regular expression.\n\nYou can check for them specifically by strict inequality or by implicit conversion to Boolean in a control statement.\n\nTrying to access properties for either leads to an exception (this is the only case).\n\n`undefined` can be changed in ECMAScript 3 and earlier. It is read-only in ES5+."},{"_id":"659a62ea50ac877b45000097","treeId":"6233ffe7781cf6071600010d","seq":6581637,"position":6,"parentId":"659a3fe450ac877b45000091","content":"### Wrapper Objects for Primitives\n\nBoolean, Number, and String have wrapper objects. Primitive values borrow methods from these wrapper objects.\n\nWrapper objects are usually only used implicitly, or for conversion. Creating new wrapper objects with a constructor should especially be avoided."},{"_id":"659a78df50ac877b45000098","treeId":"6233ffe7781cf6071600010d","seq":6581640,"position":7,"parentId":"659a3fe450ac877b45000091","content":"### Type Coercion\n\nJavaScript operators force a implicit conversion of operands to an expected primitive type. JavaScript uses an internal function, `ToPrimitive()` to do the conversion.\n\nTo perform conversion to a different type, use `Boolean()`, `Number()`, `String()`, and `Object()`."},{"_id":"659a7db750ac877b45000099","treeId":"6233ffe7781cf6071600010d","seq":6581639,"position":1,"parentId":"659a78df50ac877b45000098","content":"#### ToPrimitive(input, PreferredType?)\n\n1. If `input` is primitive, return it\n2. Depending if `input` is a number or string:\n - if a number first call `input.valueOf()` and return if primitive\n - if a string, first call `input.toString()` and return if primitive\n3. Call the other of `input.valueOf()` or `input.toString()` and return if primitive\n4. Throw a `TypeError`\n\n"},{"_id":"659a8a4c50ac877b4500009a","treeId":"6233ffe7781cf6071600010d","seq":6581660,"position":2,"parentId":"659a78df50ac877b45000098","content":"#### Boolean() - Truthy/Falsy\n\nFalsy values - converted to `false`:\n- `undefined`, `null`\n- `false`\n- `0`,`NaN`\n- `''` (empty/zero-length string)\n\nAll other values are converted to true."},{"_id":"659a901350ac877b4500009c","treeId":"6233ffe7781cf6071600010d","seq":6581683,"position":5,"parentId":"6582d65150ac877b45000086","content":"## 9. Operators\n\nOperators and Objects\nAssignment Operators\nEquality Operators: === Versus ===\nOrdering Operators\nPlus Operator `+`\nOperators for Booleans and Numbers\nSpecial Operators\nCategorizing Values via `typeof` and `instanceof`\nObject Operators"},{"_id":"659aa2ed50ac877b4500009d","treeId":"6233ffe7781cf6071600010d","seq":6581684,"position":1,"parentId":"659a901350ac877b4500009c","content":"### Operators and Objects\n\nAll operators in JavaScript coerce operands to expected primitive types. This conversion sometimes causes unexpected behavior for programmers familiar with other languages--notably, arrays cannot be concatenated via operator because they are coerced to strings first. You cannot define or overload the behavior of operators in JavaScript."},{"_id":"659aa88950ac877b4500009e","treeId":"6233ffe7781cf6071600010d","seq":6581685,"position":2,"parentId":"659a901350ac877b4500009c","content":"### Equality Operators: `===` Versus `==`\n\nWhen testing for equality, always use `===` over `==`.\n\n`NaN` is the only value that is never equal to itself."},{"_id":"659aa8aa50ac877b4500009f","treeId":"6233ffe7781cf6071600010d","seq":6581686,"position":3,"parentId":"659a901350ac877b4500009c","content":"### Special Operators\n\nThe `void` operator is a unary operator that always evaluates an expression to `undefined`. It's notably used for `javascript:` URLs in the browser. It can also be used for IIFEs."},{"_id":"659aa92a50ac877b450000a0","treeId":"6233ffe7781cf6071600010d","seq":6581687,"position":6,"parentId":"6582d65150ac877b45000086","content":"## 10. Booleans\n\nConverting to Boolean\nLogical Operators\nEquality Operators, Ordering Operators\nThe Function Boolean"},{"_id":"659aaaa850ac877b450000a1","treeId":"6233ffe7781cf6071600010d","seq":6581706,"position":7,"parentId":"6582d65150ac877b45000086","content":"## 11. Numbers\n\nJavaScript treats all numbers as 64-bit IEEE-754 numbers. JavaScript engines may optimize for integers internally.\n\nNumber Literals\nConverting to Number\nSpecial Number Values\nThe Internal Representation of Numbers\nHandling Rounding Errors\nIntegers in JavaScript\nConverting to Integer\nArithmetic Operators\nBitwise Operators\nThe Function Number\nNumber Constructor Properties\nNumber Prototype Methods\nFunctions for Numbers"},{"_id":"659abc7850ac877b450000a3","treeId":"6233ffe7781cf6071600010d","seq":6581705,"position":1,"parentId":"659aaaa850ac877b450000a1","content":"### Number Literals\n\nInteger, float, or hexadecimal."},{"_id":"659abcf850ac877b450000a4","treeId":"6233ffe7781cf6071600010d","seq":6581733,"position":2,"parentId":"659aaaa850ac877b450000a1","content":"### Converting to Number\n\nManually convert with `Number(value)` or `+value`. \n\n`parseFloat(str, radix?)` extracts the first valid floating point numeric string it finds from a string, ignoring whitespace. It parses `''` as `NaN`. It is usually better to use `Number()`.\n","deleted":false},{"_id":"659abd0b50ac877b450000a5","treeId":"6233ffe7781cf6071600010d","seq":6581734,"position":3,"parentId":"659aaaa850ac877b450000a1","content":"### Special Number Values\n\n`NaN` is a number value that is not equal to anything, including itself. It gets produced when number conversions/operations fail. You can check for `NaN` with `isNaN( )`, but you should also do a type check since isNaN( ) will coerce non-numbers.\n\nInfinity: `Infinity` and `-Infinity`. Numbers outside the range `Number.MAX_VALUE` and `Number.MIN_VALUE`, as well as values divided by zero become +/- Infinity. Check for Infinity with strict equality and `isFinite( )`.\n\nJS has both positive and negative zero, in accordance with IEEE-754. In most cases, they are indistinguishable. Numbers that approach zero beyond the precision supported become +/- `0` depending on their previous value. `Math.pow(x, -1)`, `Math.atan(x, -1), and division by the zero reveal the sign of the zero.\n"},{"_id":"659abd1750ac877b450000a6","treeId":"6233ffe7781cf6071600010d","seq":6581748,"position":4,"parentId":"659aaaa850ac877b450000a1","content":"### The Internal Representation of Numbers\n\n64-bit precision:\n- bits[53] sign\n- bits[62-52]\n- bits[51-0] fraction"},{"_id":"659abd2e50ac877b450000a8","treeId":"6233ffe7781cf6071600010d","seq":6581752,"position":6,"parentId":"659aaaa850ac877b450000a1","content":"### Handling Rounding Errors\n\nDecimal (non-binary) fractions create rounding errors. To compare non-integers, determine equality using an epsilon. The standard machine epsilon is `2^-53`"},{"_id":"659abd3a50ac877b450000a9","treeId":"6233ffe7781cf6071600010d","seq":6581754,"position":7,"parentId":"659aaaa850ac877b450000a1","content":"### Integers in JavaScript\n\nSafe signed integers: (`-2^53`, `2^53`) or (`Number.MIN_SAFE_INTEGER`, `Number.MAX_SAFE_INTEGER`)\n\nArray indices: [`0`, `2^32-1`]\nUTF-16 codes: 16 bits, unsigned\n\nFor a binary operator on integers, you must check both integers and the result to determine if it is safe."},{"_id":"659abd4550ac877b450000aa","treeId":"6233ffe7781cf6071600010d","seq":6581755,"position":8,"parentId":"659aaaa850ac877b450000a1","content":"### Converting to Integer\n\n`Math.floor()` `Math.ceil()` `Math.round()`\n\nConvert to 32-bit integers via bitwise `|0` and shift operators.\n\n`parseInt(str, radix?)` gets "},{"_id":"659abd5050ac877b450000ab","treeId":"6233ffe7781cf6071600010d","seq":6581699,"position":9,"parentId":"659aaaa850ac877b450000a1","content":"### Arithmetic Operators"},{"_id":"659abd5c50ac877b450000ac","treeId":"6233ffe7781cf6071600010d","seq":6581700,"position":10,"parentId":"659aaaa850ac877b450000a1","content":"### Bitwise Operators"},{"_id":"659abd6850ac877b450000ad","treeId":"6233ffe7781cf6071600010d","seq":6581701,"position":11,"parentId":"659aaaa850ac877b450000a1","content":"### The Function Number"},{"_id":"659abd7450ac877b450000ae","treeId":"6233ffe7781cf6071600010d","seq":6581702,"position":12,"parentId":"659aaaa850ac877b450000a1","content":"### Number Constructor Properties"},{"_id":"659abd8150ac877b450000af","treeId":"6233ffe7781cf6071600010d","seq":6581703,"position":13,"parentId":"659aaaa850ac877b450000a1","content":"### Number Prototype Methods"},{"_id":"659abd8c50ac877b450000b0","treeId":"6233ffe7781cf6071600010d","seq":6581704,"position":14,"parentId":"659aaaa850ac877b450000a1","content":"### Functions for Numbers"},{"_id":"659b005150ac877b450000b1","treeId":"6233ffe7781cf6071600010d","seq":6581761,"position":8,"parentId":"6582d65150ac877b45000086","content":"## 12. Strings\n\nString Literals\nEscaping in String Literals\nCharacter Access\nConverting to String\nComparing Strings\nConcatenating Strings\nThe Function String\nString Constructor Method\nString Instance Property length\nString Prototype Methods"},{"_id":"659b047a50ac877b450000b2","treeId":"6233ffe7781cf6071600010d","seq":6581791,"position":1,"parentId":"659b005150ac877b450000b1","content":"### String Literals\n\nSingle quoted and double quoted strings are equivalent."},{"_id":"659b04b250ac877b450000b3","treeId":"6233ffe7781cf6071600010d","seq":6581789,"position":2,"parentId":"659b005150ac877b450000b1","content":"### Escaping in String Literals\n\nLine continuations - backslash and plus operator\n\nCharacter escape sequences\nNUL character\nHexadecimal escape sequences for characters\nUnicode escape sequences"},{"_id":"659b04c350ac877b450000b4","treeId":"6233ffe7781cf6071600010d","seq":6581783,"position":3,"parentId":"659b005150ac877b450000b1","content":"### Character Access\n\n`String.charAt(i)`"},{"_id":"659b04cf50ac877b450000b5","treeId":"6233ffe7781cf6071600010d","seq":6581782,"position":4,"parentId":"659b005150ac877b450000b1","content":"### Converting to String\n\n`String( )`\n`''+value`\n`value.toString()`\n`JSON.stringify(value, replacer?, space?)`"},{"_id":"659b04da50ac877b450000b6","treeId":"6233ffe7781cf6071600010d","seq":6581781,"position":5,"parentId":"659b005150ac877b450000b1","content":"### Comparing Strings\n\ncomparison operators\n`String.prototype.localeCompare( )`"},{"_id":"659b04e650ac877b450000b7","treeId":"6233ffe7781cf6071600010d","seq":6581780,"position":6,"parentId":"659b005150ac877b450000b1","content":"### Concatenating Strings\n\n`+`\nAdding to array then joining"},{"_id":"659b04f150ac877b450000b8","treeId":"6233ffe7781cf6071600010d","seq":6581778,"position":7,"parentId":"659b005150ac877b450000b1","content":"### The Function String\n\n`String( v )`"},{"_id":"659b04fc50ac877b450000b9","treeId":"6233ffe7781cf6071600010d","seq":6581777,"position":8,"parentId":"659b005150ac877b450000b1","content":"### String Constructor Method\n\n`String.fromCharCode( c1, c2, ... )`\n`String.prototype.charCodeAt( i )`"},{"_id":"659b050850ac877b450000ba","treeId":"6233ffe7781cf6071600010d","seq":6581776,"position":9,"parentId":"659b005150ac877b450000b1","content":"### String Instance Property `length`\n\nNumber of characters in string. Immutable. Characters represented by escape codes are counted as one character."},{"_id":"659b051350ac877b450000bb","treeId":"6233ffe7781cf6071600010d","seq":6581774,"position":10,"parentId":"659b005150ac877b450000b1","content":"### String Prototype Methods\n\nExtract Substrings\nTransform\nSearch and Compare\nTest, Match, and Replace with Regular Expressions"},{"_id":"659b154a50ac877b450000bc","treeId":"6233ffe7781cf6071600010d","seq":6581796,"position":9,"parentId":"6582d65150ac877b45000086","content":"## 13. Statements\nDeclaring and Assigning Variables\nThe Bodies of Loops and Conditionals\nLoops\nConditionals\nThe with Statement\nThe debugger Statement"},{"_id":"659b184a50ac877b450000bd","treeId":"6233ffe7781cf6071600010d","seq":6581826,"position":1,"parentId":"659b154a50ac877b450000bc","content":"### Declaring and Assigning Variables\n\n`var` declares a variable. Variable declarations are hoisted. `=` assigns. They can be combined."},{"_id":"659b188950ac877b450000bf","treeId":"6233ffe7781cf6071600010d","seq":6581829,"position":3,"parentId":"659b154a50ac877b450000bc","content":"### Loops\n\nLoop body is a single statement or a code block.\n\n`[label]:`\n`break` `continue`\n\nwhile\ndo-while\nfor\nfor-in (use `Array.prototype.forEach( )` for Arrays)\nfor-each-in (Firefox only)"},{"_id":"659b189850ac877b450000c0","treeId":"6233ffe7781cf6071600010d","seq":6581814,"position":4,"parentId":"659b154a50ac877b450000bc","content":"### Conditionals\n\nif-then-else\nswitch"},{"_id":"659b18a450ac877b450000c1","treeId":"6233ffe7781cf6071600010d","seq":6581809,"position":5,"parentId":"659b154a50ac877b450000bc","content":"### The with Statement\n\nDepreciated!"},{"_id":"659b18af50ac877b450000c2","treeId":"6233ffe7781cf6071600010d","seq":6581808,"position":6,"parentId":"659b154a50ac877b450000bc","content":"### The debugger Statement\n\n`debugger;`"},{"_id":"659b224550ac877b450000c3","treeId":"6233ffe7781cf6071600010d","seq":6581831,"position":10,"parentId":"6582d65150ac877b45000086","content":"## 14. Exception Handling\n\nWhat is Exception Handling?\nException Handling in JavaScript\nError Constructors\nStack Traces\nImplementing Your Own Error Constructor"},{"_id":"659b25c850ac877b450000c5","treeId":"6233ffe7781cf6071600010d","seq":6581843,"position":2,"parentId":"659b224550ac877b450000c3","content":"### Exception Handling in JavaScript\n\nthrow\ntry-catch-finally\n\nAt least throw a `new Error( ... )` instead of a string. Environments may provide a stack trace with the error object.","deleted":false},{"_id":"659b25df50ac877b450000c6","treeId":"6233ffe7781cf6071600010d","seq":6581847,"position":3,"parentId":"659b224550ac877b450000c3","content":"### Error Constructors & Properties\n\n`Error`\n`EvalError` - not used\n`RangeError`\n`ReferenceError`\n`SyntaxError`\n`TypeError`\n`URIError`\n\nProperties\n`message`\n`name`\n`stack`"},{"_id":"659b25eb50ac877b450000c7","treeId":"6233ffe7781cf6071600010d","seq":6581850,"position":4,"parentId":"659b224550ac877b450000c3","content":"### Stack Traces\n\nYou can set the `message` property of the error. Engines may support the `stack` property."},{"_id":"659b25f850ac877b450000c8","treeId":"6233ffe7781cf6071600010d","seq":6581836,"position":5,"parentId":"659b224550ac877b450000c3","content":"### Implementing Your Own Error Constructor"},{"_id":"659b344b50ac877b450000c9","treeId":"6233ffe7781cf6071600010d","seq":6581860,"position":11,"parentId":"6582d65150ac877b45000086","content":"## 15. Functions\n\nThe Three Roles of Functions in JavaScript\nTerminology: “Parameter” Versus “Argument”\nDefining Functions\nHoisting\nThe Name of a Function\nWhich Is Better: A Function Declaration or a Function Expression?\nMore Control over Function Calls: call(), apply(), and bind()\nHandling Missing or Extra Parameters\nNamed Parameters"},{"_id":"659b39e750ac877b450000ca","treeId":"6233ffe7781cf6071600010d","seq":6581878,"position":1,"parentId":"659b344b50ac877b450000c9","content":"### The Three Roles of Functions in JavaScript\n\nNonmethod function (“normal function”)\nConstructor\nMethod"},{"_id":"659b3a0750ac877b450000cb","treeId":"6233ffe7781cf6071600010d","seq":6581880,"position":2,"parentId":"659b344b50ac877b450000c9","content":"### Terminology: “Parameter” Versus “Argument”\n\nparameters - (formal parameters/arguments) used in the function definition\n\narguments - (actual parameters/arguments) in the function invocation"},{"_id":"659b3a1d50ac877b450000cc","treeId":"6233ffe7781cf6071600010d","seq":6581881,"position":3,"parentId":"659b344b50ac877b450000c9","content":"### Defining Functions\n\nFunction Expressions - anonymous or named\nFunction Declarations - hoisted\nThe Function Constructor - Similar to `eval`. Don't use this in general."},{"_id":"659b3a3150ac877b450000cd","treeId":"6233ffe7781cf6071600010d","seq":6581882,"position":4,"parentId":"659b344b50ac877b450000c9","content":"### Hoisting\n\nOnly function declarations are completely hoisted. `var` is hoisted, but assigning a function expression is not."},{"_id":"659b3a4350ac877b450000ce","treeId":"6233ffe7781cf6071600010d","seq":6581883,"position":5,"parentId":"659b344b50ac877b450000c9","content":"### The Name of a Function\n\nMost JS engines support the property `name`, which is useful for debugging."},{"_id":"659b3a5450ac877b450000cf","treeId":"6233ffe7781cf6071600010d","seq":6581884,"position":6,"parentId":"659b344b50ac877b450000c9","content":"### Which Is Better: A Function Declaration or a Function Expression?"},{"_id":"659b3a9f50ac877b450000d0","treeId":"6233ffe7781cf6071600010d","seq":6581885,"position":7,"parentId":"659b344b50ac877b450000c9","content":"### More Control over Function Calls: call(), apply(), and bind()\n\n`func.apply(thisValue, argArray)`\n`func.bind(thisValue, arg1, ..., argN)`"},{"_id":"659b3aae50ac877b450000d1","treeId":"6233ffe7781cf6071600010d","seq":6581887,"position":8,"parentId":"659b344b50ac877b450000c9","content":"### Handling Missing or Extra Parameters\n\nMore actual parameters than formal parameters - extra parameters ignored but are still in `arguments`\n\nFewer actual parameters than formal parameters - missing parameters get `undefined`\n\n`arguments` - array-like object--has `length` and can access elements with `[]` but no other array methods.\n\nStrict vs Sloppy mode: `callee` property is depreciated and is not allowed in strict mode. In sloppy mode, arguments change when parameters change, but not in strict mode. Strict mode prevents assigning to `arguments`.\n\nMandatory Parameters, Enforcing a Minimum Arity\n\nOptional Parameters\n\nSimulating Pass-by-Reference Parameters - enclose in an array.\n\nPitfall: Unexpected Optional Parameters"},{"_id":"659b3abf50ac877b450000d2","treeId":"6233ffe7781cf6071600010d","seq":6581888,"position":9,"parentId":"659b344b50ac877b450000c9","content":"### Named Parameters\n\nJavaScript doesn't support named parameters directly. Simulate by passing in an object."},{"_id":"659b6a1150ac877b450000d3","treeId":"6233ffe7781cf6071600010d","seq":6581906,"position":12,"parentId":"6582d65150ac877b45000086","content":"## 16. Variables: Scopes, Environments, and Closures\n\nDeclaring a Variable\nBackground: Static Versus Dynamic\nBackground: The Scope of a Variable\nVariables Are Function-Scoped\nVariable Declarations Are Hoisted\nIntroducing a New Scope via an IIFE\nGlobal Variables\nThe Global Object\nEnvironments: Managing Variables\nClosures: Functions Stay Connected to Their Birth Scopes"},{"_id":"659b70e550ac877b450000d4","treeId":"6233ffe7781cf6071600010d","seq":6581918,"position":1,"parentId":"659b6a1150ac877b450000d3","content":"### Declaring a Variable"},{"_id":"659b712550ac877b450000d5","treeId":"6233ffe7781cf6071600010d","seq":6581919,"position":2,"parentId":"659b6a1150ac877b450000d3","content":"### Background: Static Versus Dynamic\n\nStatically (or lexically)\nDynamically"},{"_id":"659b713750ac877b450000d6","treeId":"6233ffe7781cf6071600010d","seq":6581920,"position":3,"parentId":"659b6a1150ac877b450000d3","content":"### Background: The Scope of a Variable\n\nThe scope of a variable\nLexical scoping\nNested scopes\nShadowing"},{"_id":"659b714650ac877b450000d7","treeId":"6233ffe7781cf6071600010d","seq":6581921,"position":4,"parentId":"659b6a1150ac877b450000d3","content":"### Variables Are Function-Scoped"},{"_id":"659b715550ac877b450000d8","treeId":"6233ffe7781cf6071600010d","seq":6581983,"position":5,"parentId":"659b6a1150ac877b450000d3","content":"### Variable Declarations Are Hoisted"},{"_id":"659b716550ac877b450000d9","treeId":"6233ffe7781cf6071600010d","seq":6581989,"position":6,"parentId":"659b6a1150ac877b450000d3","content":"### Introducing a New Scope via an IIFE\n\nIt is immediately invoked\nIt must be an expression\nThe trailing semicolon is required\n\nIIFE Variation: Prefix Operators\nIIFE Variation: Already Inside Expression Context\nIIFE Variation: An IIFE with Parameters\nIIFE Applications"},{"_id":"659b717350ac877b450000da","treeId":"6233ffe7781cf6071600010d","seq":6582101,"position":7,"parentId":"659b6a1150ac877b450000d3","content":"### Global Variables\n\nPITFALL: ASSIGNING TO AN UNDECLARED VARIABLE MAKES IT GLOBAL"},{"_id":"659b718150ac877b450000db","treeId":"6233ffe7781cf6071600010d","seq":6582115,"position":8,"parentId":"659b6a1150ac877b450000d3","content":"### The Global Object\n\nBrandon Eich considers the global object one of his biggest regrets.\n\nBrowsers - `window` - standardized as part of the DOM, not ES5\nNode.js - `global`\n\nUse Cases for window"},{"_id":"659b718e50ac877b450000dc","treeId":"6233ffe7781cf6071600010d","seq":6582194,"position":9,"parentId":"659b6a1150ac877b450000d3","content":"### Environments: Managing Variables\n\nDynamic dimension: invoking functions - stack of execution contexts\n\nLexical (static) dimension: staying connected to your surrounding scopes - chain of environments\n"},{"_id":"659b719c50ac877b450000dd","treeId":"6233ffe7781cf6071600010d","seq":6582206,"position":10,"parentId":"659b6a1150ac877b450000d3","content":"### Closures: Functions Stay Connected to Their Birth Scopes\n\nHandling Closures via Environments\n"},{"_id":"6645536b1f0b9082010000de","treeId":"6233ffe7781cf6071600010d","seq":6697680,"position":13,"parentId":"6582d65150ac877b45000086","content":"## 17. Objects and Inheritance\n\nLayer 1: Object-orientation with single objects\nLayer 2: Prototype chains of objects\nLayer 3: Constructors as factories for instances\nLayer 5: Subclassing & Subconstructors"},{"_id":"666dc997ea29b089b10000ed","treeId":"6233ffe7781cf6071600010d","seq":6723882,"position":0.5,"parentId":"6645536b1f0b9082010000de","content":"### Cheat Sheet: Working With Objects"},{"_id":"666dcd7bea29b089b10000ee","treeId":"6233ffe7781cf6071600010d","seq":6723852,"position":1,"parentId":"666dc997ea29b089b10000ed","content":"#### Object literals"},{"_id":"666dcdbfea29b089b10000ef","treeId":"6233ffe7781cf6071600010d","seq":6723853,"position":2,"parentId":"666dc997ea29b089b10000ed","content":"#### Dot operator"},{"_id":"666dcdd2ea29b089b10000f0","treeId":"6233ffe7781cf6071600010d","seq":6723854,"position":3,"parentId":"666dc997ea29b089b10000ed","content":"#### Bracket operator"},{"_id":"666dcdddea29b089b10000f1","treeId":"6233ffe7781cf6071600010d","seq":6723855,"position":4,"parentId":"666dc997ea29b089b10000ed","content":"#### Getting and setting the prototype"},{"_id":"666dcde8ea29b089b10000f2","treeId":"6233ffe7781cf6071600010d","seq":6723856,"position":5,"parentId":"666dc997ea29b089b10000ed","content":"#### Iteration and detection of properties"},{"_id":"666dce01ea29b089b10000f3","treeId":"6233ffe7781cf6071600010d","seq":6723857,"position":6,"parentId":"666dc997ea29b089b10000ed","content":"#### Getting and defining properties via descriptors"},{"_id":"666dce0fea29b089b10000f4","treeId":"6233ffe7781cf6071600010d","seq":6723858,"position":7,"parentId":"666dc997ea29b089b10000ed","content":"#### Protecting objects"},{"_id":"666dce19ea29b089b10000f5","treeId":"6233ffe7781cf6071600010d","seq":6723859,"position":8,"parentId":"666dc997ea29b089b10000ed","content":"#### Methods of all objects"},{"_id":"664699c11f0b9082010000df","treeId":"6233ffe7781cf6071600010d","seq":6723887,"position":1,"parentId":"6645536b1f0b9082010000de","content":"### Layer 1. Object-orientation with single objects\n\nKinds of Properties\nObject Literals\nDot Operator\nUnusual Property Keys\nBracket Operator\nConverting Any Value to an Object"},{"_id":"664785301f0b9082010000e5","treeId":"6233ffe7781cf6071600010d","seq":6697614,"position":1.75,"parentId":"6645536b1f0b9082010000de","content":"### this as an Implicit Parameter of Function and Methods\n\ncall( ), apply( ), bind( )\napply( ) for constructors\npitfall: losing `this` when extracting a method\npitfall: functions inside methods shadow `this`"},{"_id":"66469a771f0b9082010000e0","treeId":"6233ffe7781cf6071600010d","seq":6723804,"position":2,"parentId":"6645536b1f0b9082010000de","content":"### Layer 2. Prototype chains of objects\n\nInheritance. Overriding. Sharing data between objects via a prototype. Getting and setting the prototype. `__proto__`. Setting and deleting affects only own properties.\n\n*Iteration and Detection of Properties.* Listing own property keys. Listing all property keys. Checking whether a property exists.\n\n*Best Practices: Iterating over Own Properties.*\n\n*Accessors (Getters and Setters).* Defining accessors via an object literal. Defining accessors via property\ndescriptors. Accessors and inheritance.\n\n*Property Attributes and Property Descriptors*. Property Attributes. Property Descriptors. Getting and Defining Properties via descriptors. Copying an object. Properties: definition versus assignment. Inherited read-only properties can’t be assigned to. Enumerability: best practices.\n\n*Protecting Objects.* Preventing extensions. Sealing. Freezing. Pitfall: protection is shallow."},{"_id":"666da486ea29b089b10000ec","treeId":"6233ffe7781cf6071600010d","seq":6723675,"position":1,"parentId":"66469a771f0b9082010000e0","content":"#### Overview\nInheritance\nOverriding\nSharing data between objects via a prototype\nGetting and setting the prototype\n`__proto__`\nSetting and deleting affects only own properties\n#### Iteration and Detection of Properties\n\nListing own property keys\nListing all property keys\nChecking whether a property exists\n#### Best Practices: Iterating over Own Properties\n#### Accessors (Getters and Setters)\n\nDefining Accessors via an Object Literal\nDefining Accessors via Property Descriptors\nAccessors and Inheritance\n#### Property Attributes and Property Descriptors\n\nProperty Attributes\nProperty Descriptors\nGetting and Defining Properties via Descriptors\nCopying an Object\nProperties: Definition Versus Assignment\nInherited Read-Only Properties Can’t Be Assigned To\nEnumerability: Best Practices\n\n#### Protecting Objects\nPreventing Extensions\nSealing\nFreezing\nPitfall: Protection Is Shallow"},{"_id":"66469ad31f0b9082010000e1","treeId":"6233ffe7781cf6071600010d","seq":6723974,"position":3,"parentId":"6645536b1f0b9082010000de","content":"### Layer 3. Constructors as factories for instances\n\nWhat is a constructor in JavaScript? The new operator implemented in JavaScript. Terminology: the two prototypes. The constructor property of instances. The `instanceof` operator. Tips for implementing constructors.\n\n*Data in Prototype Properties.* Avoid prototype properties with initial values for instance properties. Avoid nonpolymorphic prototype properties. Polymorphic prototype properties.\n\n*Keeping Data Private.* Private data in the environment of a constructor (Crockford Privacy Pattern). Private data in properties with marked keys. Private data in properties with reified keys. Keeping global data private via IIFEs."},{"_id":"666e01c0ea29b089b10000f6","treeId":"6233ffe7781cf6071600010d","seq":6724628,"position":1,"parentId":"66469ad31f0b9082010000e1","content":"Constructor overview\n\n`.prototype`\n`.constructor`\n`instanceof`\n\nThe instanceof operator\n- syntax: `value instanceof Constr`\n- Identical to: `Constr.prototype.isPrototypeOf(value)`\n- Pitfall: objects that are not instances of Object\n- Pitfall: crossing realms (frames or windows)\n\nTips for implementing constructors:\n- use strict mode to protect against forgetting `new`\n- Constructors can return arbitrary objects"},{"_id":"666e4e2dea29b089b10000fc","treeId":"6233ffe7781cf6071600010d","seq":6724594,"position":0.25,"parentId":"666e01c0ea29b089b10000f6","content":"What the `new` operator actually does"},{"_id":"666e4c2fea29b089b10000f9","treeId":"6233ffe7781cf6071600010d","seq":6724585,"position":0.5,"parentId":"666e01c0ea29b089b10000f6","content":"`constructor` property of instances\n\nUse cases for the constructor property:\n\n- Identifying/taking different action on an object based on its constructor (only works on direct instances of a constructor)\n- Determining the name of an object's constructor with `.constructor.name`. (Not all JS engines support function property `name`.)\n- Creating a new object with the same constructor\n- Referring to a superconstructor\n\nBest practice: make sure that for a constructor `C`, `C.prototype.constructor === C` is `true`. Functions have this set up correctly by default. Avoid replacing the `prototype` object, and if you do, manually assign the right value to `constructor`."},{"_id":"666e3966ea29b089b10000f8","treeId":"6233ffe7781cf6071600010d","seq":6724624,"position":1,"parentId":"666e01c0ea29b089b10000f6","content":"#### The `instanceof` operator\n```\nvalue instanceof Constr\n```\n\nChecks the whole prototype chain. Always returns false for primitive operands. Throws an exception if rhs operand isn't a function.\n\nIdentical to: \n```\nConstr.prototype.isPrototypeOf(value)\n```\n\nPitfall: objects that aren't instances of `Object` don't get identified as an object by `instanceof`.\n\nPitfall: `instanceof` might not work across different frames and windows, which each have their own global variables.\n\nWorkarounds:\n- Use special methods like `Array.isArray()`\n- Avoid crossing realms (windows/frames) by using `postMessage( )` to copy over objects\n- Compare the `.constructor.name`\n- Use a property on the prototype to mark instances"},{"_id":"666e4ee8ea29b089b10000fd","treeId":"6233ffe7781cf6071600010d","seq":6724611,"position":2,"parentId":"666e01c0ea29b089b10000f6","content":"Tips for implementing constuctors\n\n_Use strict mode to protect against forgetting to use `new`._ Strict mode will raise an exception:\n\n```\nTypeError: Cannot set property 'name' of undefined\n```\n\n_Returning arbitrary objects from a constructor_. JavaScript can return arbitrary objects, allowing you to use them as factory methods.\n\n```\nfunction Expression(str) {\n if (...) {\n return new Addition(..);\n } else if (...) {\n return new Multiplication(...);\n } else {\n throw new ExpressionException(...);\n }\n}\n...\nvar expr = new Expression(someStr);\n```"},{"_id":"666e5d9cea29b089b10000fe","treeId":"6233ffe7781cf6071600010d","seq":6724718,"position":2,"parentId":"66469ad31f0b9082010000e1","content":"#### Data in Prototype Properties\n\nWhy you usually shouldn't put data in prototype properties.\n\nWhy avoid prototype properties with initial values for instance properties: _mutating_ the value on the instance before it's overwritten with an own property will change the prototype default value!\n\nAvoid nonpolymorphic prototype properties, like constants. Use variables instead.\n\nPolymorphic prototype properties can be used for tagging instances across realms.\n\n"},{"_id":"666e6a4aea29b089b10000ff","treeId":"6233ffe7781cf6071600010d","seq":6724691,"position":1,"parentId":"666e5d9cea29b089b10000fe","content":"Avoid prototype properties with initial values\n\nDo this instead to create a new property on the instance with a default value:\n```\nfunction Names(data) {\n this.data = data || [];\n}\n```\n\nWhen you might use prototype property with an initial value:\n\nLazy instantiation of properties\n```\nfunction Names(data) {\n if (data) this.data = data;\n}\nNames.prototype = {\n constructor: Names, // (1)\n get data() {\n // Define, don’t assign\n // => avoid calling the (nonexistent) setter\n Object.defineProperty(this, 'data', {\n value: [],\n enumerable: true,\n configurable: false,\n writable: false\n });\n return this.data;\n }\n};\n```\n "},{"_id":"666e87b4ea29b089b1000100","treeId":"6233ffe7781cf6071600010d","seq":6724912,"position":3,"parentId":"66469ad31f0b9082010000e1","content":"#### Keeping Data Private\n\nJavaScript doesn't have a built-in means for data privacy. There are three main patterns for using data privacy:\n\n***Private data in the environment of a constructor*** (_Crockford privacy pattern_) - functions created as part of a constructor are part of that constructor's closure. They can act as _privileged methods_ that access data that is part of the constructor's environment. Not very elegant, may be slower, consumes more memory, but it's completely secure.\n\n***Private data in properties with marked keys*** (_private by convention_) - usually with a naming convention like an underscore. This offers a more natural coding style, but it pollutes the property namespace because they'll show up as normal properties. It can also lead to key clashes. They can be accessed normally, which can be flexible for unit tests and stuff.\n\n***Private data in properties with reified keys*** - storing the key value in a variable. This avoids key clashes and lets you use UUIDs that can have unique values at runtime.\n\n***You can keep global data private via IIFEs***: attaching it to a singleton object, keeping it private to a constructor, attaching it to a method"},{"_id":"666e93c9ea29b089b1000101","treeId":"6233ffe7781cf6071600010d","seq":6724736,"position":1,"parentId":"666e87b4ea29b089b1000100","content":"Private Data in the Environment of a Constructor (Crockford Privacy Pattern)\n\nPublic properties\n```\nConstr.prototype.publicMethod = ...;\n```\n\n```\nfunction Constr(...) {\n this.publicData = ...;\n ...\n}\n```\n\nPrivate values\n```\nfunction Constr(...) {\n ...\n var that = this; // make accessible to private functions\n\n var privateData = ...;\n\n function privateFunction(...) {\n // Access everything\n privateData = ...;\n\n that.publicData = ...;\n that.publicMethod(...);\n }\n ...\n}\n```\n\nPrivileged methods\n```\nfunction Constr(...) {\n ...\n this.privilegedMethod = function (...) {\n // Access everything\n privateData = ...;\n privateFunction(...);\n\n this.publicData = ...;\n this.publicMethod(...);\n };\n}\n```"},{"_id":"666eb0e4ea29b089b1000102","treeId":"6233ffe7781cf6071600010d","seq":6724801,"position":2,"parentId":"666e87b4ea29b089b1000100","content":"Private Data in Properties with Reified Keys\n\n```\nvar StringBuilder = function () {\n var KEY_BUFFER = '_StringBuilder_buffer';\n\n function StringBuilder() {\n this[KEY_BUFFER] = [];\n }\n StringBuilder.prototype = {\n constructor: StringBuilder,\n add: function (str) {\n this[KEY_BUFFER].push(str);\n },\n toString: function () {\n return this[KEY_BUFFER].join('');\n }\n };\n return StringBuilder;\n}();\n```\nNote the IIFE."},{"_id":"666eb326ea29b089b1000103","treeId":"6233ffe7781cf6071600010d","seq":6724918,"position":3,"parentId":"666e87b4ea29b089b1000100","content":"Keeping Global Data Private via IIFEs\n\nAttaching private global data to a singleton object\n```\nvar obj = function () { // open IIFE\n\n // public\n var self = {\n publicMethod: function (...) {\n privateData = ...;\n privateFunction(...);\n },\n publicData: ...\n };\n\n // private\n var privateData = ...;\n function privateFunction(...) {\n privateData = ...;\n self.publicData = ...;\n self.publicMethod(...);\n }\n\n return self;\n}(); // close IIFE\n```\n\nKeeping global data private to all of a constructor\n```\nvar StringBuilder = function () { // open IIFE\n var KEY_BUFFER = '_StringBuilder_buffer_' + uuid.v4();\n\n function StringBuilder() {\n this[KEY_BUFFER] = [];\n }\n StringBuilder.prototype = {\n // Omitted: methods accessing this[KEY_BUFFER]\n };\n return StringBuilder;\n}(); // close IIFE\n```\n\nAttaching global data to a method\n```\nvar obj = {\n method: function () { // open IIFE\n\n // method-private data\n var invocCount = 0;\n\n return function () {\n invocCount++;\n console.log('Invocation #'+invocCount);\n return 'result';\n };\n }() // close IIFE\n};\n```"},{"_id":"66469b4c1f0b9082010000e2","treeId":"6233ffe7781cf6071600010d","seq":6724919,"position":4,"parentId":"6645536b1f0b9082010000de","content":"### Layer 4. Subconstructors\n\n#### Overview\nInheriting Instance Properties\nInheriting Prototype Properties\nEnsuring That `instanceof` Works\nOverriding a Method\nMaking a Supercall\nAvoiding Hardcoding the Name of the Superconstructor\nExample: Constructor Inheritance in Use\nExample: The Inheritance Hierarchy of Built-in Constructors\nAntipattern: The Prototype Is an Instance of the Superconstructor\n\n#### Methods of All Objects\nConversion to Primitive\nObject.prototype.toLocaleString()\nPrototypal Inheritance and Properties\n\n#### Generic Methods: Borrowing Methods from Prototypes\nAccessing Object.prototype and Array.prototype via Literals\nExamples of Calling Methods Generically\nArray-Like Objects and Generic Methods\nA List of All Generic Methods\n\n#### Pitfalls: Using an Object as a Map\nPitfall 1: Inheritance Affects Reading Properties\nPitfall 2: Overriding Affects Invoking Methods\nPitfall 3: The Special Property `__proto__`\nThe dict Pattern: Objects Without Prototypes Are Better Maps\nBest Practices\n"},{"_id":"666edf41ea29b089b1000104","treeId":"6233ffe7781cf6071600010d","seq":6724967,"position":1,"parentId":"66469b4c1f0b9082010000e2","content":"#### Subconstructor Howto\n\nFor two constructors `Super` and `Sub` we want:\n\n- Inheriting instance properties.\n- Inheriting prototype properties.\n- `instanceof` to work for instances\n- Overridding of methods\n- Being able to call an original from an overridden method"},{"_id":"666f04dfea29b089b1000109","treeId":"6233ffe7781cf6071600010d","seq":6725061,"position":0.5,"parentId":"666edf41ea29b089b1000104","content":"Utility function\n\n```\nfunction subclasses(SubC, SuperC) {\n var subProto = Object.create(SuperC.prototype);\n // Save `constructor` and, possibly, other methods\n copyOwnPropertiesFrom(subProto, SubC.prototype);\n SubC.prototype = subProto;\n SubC._super = SuperC.prototype;\n};\n```"},{"_id":"666ee561ea29b089b1000105","treeId":"6233ffe7781cf6071600010d","seq":6725057,"position":1,"parentId":"666edf41ea29b089b1000104","content":"Inheriting Instance Properties\n\n```\nfunction Sub(prop1, prop2, prop3, prop4) {\n Sub._super.call(this, prop1, prop2); // (1)\n this.prop3 = prop3; // (2)\n this.prop4 = prop4; // (3)\n}\n```\n\nThe trick is to not invoke `Super` via `new`."},{"_id":"666ee77bea29b089b1000106","treeId":"6233ffe7781cf6071600010d","seq":6725014,"position":2,"parentId":"666edf41ea29b089b1000104","content":"Inheriting Prototype Properties / making `instanceof` work for instances\n\nGive `sub.prototype` the prototype `super.prototype`.\n\n```\nSub.prototype = Object.create(Sub._super.prototype);\nSub.prototype.constructor = Sub;\nSub.prototype.methodB = ...;\nSub.prototype.methodC = ...;\n```"},{"_id":"666ef3d2ea29b089b1000108","treeId":"6233ffe7781cf6071600010d","seq":6725013,"position":3,"parentId":"666edf41ea29b089b1000104","content":"Overriding a Method vs. Making a Supercall\n\nMethods added to `Sub.prototype` will override methods with the same name in `Super.prototype`.\n\nA _home object_ of a method is the object that owns the property that contains the method.\n\nTo call a supermethod, skip the home object of the current method, search for a method with that name, and invoke with the current `this`.\n\n```\nSub.prototype.methodB = function (x, y) {\n var superResult = Sub._super.prototype.methodB.call(this, x, y); // (1)\n return this.prop3 + ' ' + superResult;\n}\n```"},{"_id":"666f095dea29b089b100010b","treeId":"6233ffe7781cf6071600010d","seq":6725063,"position":4,"parentId":"666edf41ea29b089b1000104","content":"Example\n\nSuperconstructor\n```\nfunction Person(name) {\n this.name = name;\n}\nPerson.prototype.describe = function () {\n return 'Person called '+this.name;\n};\n```\n\nSubconstructor\n```\nfunction Employee(name, title) {\n Person.call(this, name);\n this.title = title;\n}\nEmployee.prototype = Object.create(Person.prototype);\nEmployee.prototype.constructor = Employee;\nEmployee.prototype.describe = function () {\n return Person.prototype.describe.call(this)+' ('+this.title+')';\n};\n\n```"},{"_id":"666f0cd6ea29b089b100010d","treeId":"6233ffe7781cf6071600010d","seq":6725144,"position":2,"parentId":"66469b4c1f0b9082010000e2","content":"#### `Object.prototype` methods\n\nConversion to Primitive\n```\nObject.prototype.toString()\nObject.prototype.valueOf()\nObject.prototype.toLocaleString()\n```\n\nPrototypal Inheritance and Properties\n```\nObject.prototype.isPrototypeOf(obj)\nObject.prototype.hasOwnProperty(key)\nObject.prototype.propertyIsEnumerable(propKey)\n```"},{"_id":"666f1849ea29b089b100010e","treeId":"6233ffe7781cf6071600010d","seq":6725146,"position":3,"parentId":"66469b4c1f0b9082010000e2","content":"#### Generic Methods"},{"_id":"666f1e66ea29b089b100010f","treeId":"6233ffe7781cf6071600010d","seq":6725156,"position":1,"parentId":"666f1849ea29b089b100010e","content":"#### Accessing Object.prototype and Array.prototype via Literals\n\nJust use the empty object `{}` instead of `Object.prototype` and `[]` instead of `Array.prototype`."},{"_id":"666f2766ea29b089b1000110","treeId":"6233ffe7781cf6071600010d","seq":6725165,"position":2,"parentId":"666f1849ea29b089b100010e","content":"Examples\n\n```\n> var arr1 = [ 'a', 'b' ];\n> var arr2 = [ 'c', 'd' ];\n\n> [].push.apply(arr1, arr2)\n4\n> arr1\n[ 'a', 'b', 'c', 'd' ]\n```\n\n```\n> Array.prototype.join.call('abc', '-')\n'a-b-c'\n```\n\n```\n> [].map.call('abc', function (x) { return x.toUpperCase() })\n[ 'A', 'B', 'C' ]\n```\n\n```\n> 'abc'.split('').map(function (x) { return x.toUpperCase() })\n[ 'A', 'B', 'C' ]\n```\n\n```\n> String.prototype.toUpperCase.call(true)\n'TRUE'\n> String.prototype.toUpperCase.call(['a','b','c'])\n'A,B,C'\n```\n\n```\n> var fakeArray = { 0: 'a', 1: 'b', length: 2 };\n> Array.prototype.join.call(fakeArray, '-')\n'a-b'\n```\n\n```\n> var obj = {};\n> Array.prototype.push.call(obj, 'hello');\n1\n> obj\n{ '0': 'hello', length: 1 }\n```\n\n```\nfunction logArgs() {\n Array.prototype.forEach.call(arguments, function (elem, i) {\n console.log(i+'. '+elem);\n });\n}\n```"},{"_id":"666f2e01ea29b089b1000112","treeId":"6233ffe7781cf6071600010d","seq":6725164,"position":3,"parentId":"666f1849ea29b089b100010e","content":"Array-Like Objects and Generic Methods\n\n`arguments`\nDOM node lists - returned by document.getElementsBy*()\nStrings\n\nArray-like objects need elements accessible by integer indices and a `length` property. Array methods need these to be readable, and sometimes writable."},{"_id":"666f3ad2ea29b089b1000113","treeId":"6233ffe7781cf6071600010d","seq":6725192,"position":4.5,"parentId":"66469b4c1f0b9082010000e2","content":"#### Pitfalls: Using an Object as a Map\n\nPitfall 1: Inheritance Affects Reading Properties\nPitfall 2: Overriding Affects Invoking Methods\nPitfall 3: The Special Property __proto__\n\nCreating an object without a prototype (`Object.create(null)`) avoids all of these pitfalls."},{"_id":"667a29425a9b62091c00010d","treeId":"6233ffe7781cf6071600010d","seq":6733445,"position":14,"parentId":"6582d65150ac877b45000086","content":"## 18. Arrays\n\nOverview\nCreating Arrays\nArray Indices\nlength\nHoles in Arrays\nArray Constructor Method\nArray Prototype Methods\nAdding and Removing Elements (Destructive)\nSorting and Reversing Elements (Destructive)\nConcatenating, Slicing, Joining (Nondestructive)\nSearching for Values (Nondestructive)\nIteration (Nondestructive)\nBest Practices: Iterating over Arrays"},{"_id":"667a35005a9b62091c00010e","treeId":"6233ffe7781cf6071600010d","seq":6733424,"position":1,"parentId":"667a29425a9b62091c00010d","content":"### Overview\n\nArray syntax\nArrays Are Maps, Not Tuples\nArrays Can Also Have Properties"},{"_id":"6686b3445a9b62091c00011c","treeId":"6233ffe7781cf6071600010d","seq":6745910,"position":1,"parentId":"667a35005a9b62091c00010e","content":"#### Array Syntax\n\n```\nvar arr = ['a', 'b', 'c'];\narr.length;\narr.length = 2;\narr[arr.length] = 'd';\narr.push('e');\nvar e = arr.pop();\n\n```"},{"_id":"6686b7a25a9b62091c00011d","treeId":"6233ffe7781cf6071600010d","seq":6745917,"position":2,"parentId":"667a35005a9b62091c00010e","content":"#### Arrays are Maps, Not Tuples\n\nThe `Array` type is an object with properties that have integer indices as names.\n\nThe elements of an Array are not necessarily contiguous, and Arrays can have \"holes\", or missing indices."},{"_id":"6686bbf35a9b62091c00011e","treeId":"6233ffe7781cf6071600010d","seq":6745919,"position":3,"parentId":"667a35005a9b62091c00010e","content":"#### Arrays Can Also Have Properties\n\nArrays work like any other object. You can add arbitrary properties to them. These new properties are not considered array elements by array methods."},{"_id":"667a36645a9b62091c00010f","treeId":"6233ffe7781cf6071600010d","seq":6745920,"position":2,"parentId":"667a29425a9b62091c00010d","content":"### Creating Arrays\n\nArray Literals/The Array Constructor\nMultidimensional Arrays"},{"_id":"6686bf2f5a9b62091c000120","treeId":"6233ffe7781cf6071600010d","seq":6745925,"position":1,"parentId":"667a36645a9b62091c00010f","content":"#### Array Literals/Array Constructor\n\n```\n// Array literal\nvar arr = ['a', 'b', 'c']\n```\n\n**Array Constructor**\n\nWhy the `Array( )` constructor is problematic:\n\n_Creating an empty array with a given length_\n\n```\n// creates an array object with length 2\nvar arr = new Array(2);\n// elements at indices are still undefined\n```\n\n_Initializing an array with elements via constructor_\n`Array( )` will try to parse a numeric argument as a length\n```\n// Array with two holes, not [2]\nvar arr = new Array(2);\n// RangeError: Invalid array length\narr = new Array(9.9);\n```"},{"_id":"6686cb2a5a9b62091c000121","treeId":"6233ffe7781cf6071600010d","seq":6745926,"position":2,"parentId":"667a36645a9b62091c00010f","content":"#### Multidimensional Arrays\n\nCreate multidimensional arrays by nesting arrays. Make sure to create the rows (outer arrays). You have to do this with a loop (since a constructor will just set the `length` of the outer array)\n\n"},{"_id":"667a39805a9b62091c000110","treeId":"6233ffe7781cf6071600010d","seq":6745934,"position":3,"parentId":"667a29425a9b62091c00010d","content":"### Array Indices\n\nindices ***i*** go from 0 ≤ i < 2^32−1\nmax `length` is 2^32-1\n\nIndices out of range are treated as string property keys.\n\nThe in Operator and Indices\nDeleting Array Elements\nArray Indices in Detail"},{"_id":"6686d5ae5a9b62091c000122","treeId":"6233ffe7781cf6071600010d","seq":6745940,"position":1,"parentId":"667a39805a9b62091c000110","content":"#### The in Operator and Indices\n\n"},{"_id":"6686d6b35a9b62091c000123","treeId":"6233ffe7781cf6071600010d","seq":6746056,"position":2,"parentId":"667a39805a9b62091c000110","content":"#### Deleting Array Elements\n\n`delete` works on array elements but doesn't update `length` or shift elements. It creates a hole.\n\nTo delete elements without leaving a hole, use `Array.prototype.splice()`\n\n```\n// remove i\narr.splice(i, 1);\n// remove j through k\narr.splice(j,k-j+1);\n// remove m up to but not including n\narr.splice(m, n-m);\n// remove the third last element and after\narr.splice(-3);\n```"},{"_id":"6686d7215a9b62091c000124","treeId":"6233ffe7781cf6071600010d","seq":6745946,"position":3,"parentId":"667a39805a9b62091c000110","content":"#### Array Indices in Detail\n\nIndices aren't numbers, but string property keys.\n\nFor a key ***P*** that is a valid array index:\n- `ToString(ToUint32(P)) === P` is true\n- `ToUint32(P) !== Math.pow(2,32)-1`\n"},{"_id":"667a3b155a9b62091c000111","treeId":"6233ffe7781cf6071600010d","seq":6746021,"position":4,"parentId":"667a29425a9b62091c00010d","content":"### length\n\n`length` only keeps track of the highest index. It doesn't count nonholes.\n\nTrying to construct an array with length > 2^32-1 will cause a `RangeError: Invalid array length`.\n\nManually Increasing the Length of an Array\nDecreasing the Length of an Array"},{"_id":"668705a35a9b62091c000125","treeId":"6233ffe7781cf6071600010d","seq":6746016,"position":1,"parentId":"667a3b155a9b62091c000111","content":"#### Manually Increasing the Length of an Array\n\nChanging length only creates holes (doesn't create new, empty array elements)."},{"_id":"6687089b5a9b62091c000126","treeId":"6233ffe7781cf6071600010d","seq":6746019,"position":2,"parentId":"667a3b155a9b62091c000111","content":"#### Decreasing the Length of an Array\n\nThis _does_ actually delete elements (trying to access afterwards will return `undefined`)\n\nYou can clear an array by setting `length` to `0`. This clears the array for all variables accessing the object. But this operation can be slow and it is easier to create a new, empty array."},{"_id":"667a3de45a9b62091c000112","treeId":"6233ffe7781cf6071600010d","seq":6745824,"position":5,"parentId":"667a29425a9b62091c00010d","content":"### Holes in Arrays\n\nCreating Holes\nSparse Arrays Versus Dense Arrays\nWhich Operations Ignore Holes, and Which Consider Them?\nRemoving Holes from Arrays"},{"_id":"668710655a9b62091c000127","treeId":"6233ffe7781cf6071600010d","seq":6746028,"position":1,"parentId":"667a3de45a9b62091c000112","content":"#### Creating Holes / Sparse Arrays\n\nYou can create holes by omitting values in literals and assigning to nonconsecutive indices.\n\nTrying to access a hole returns `undefined`. Unlike an actual `undefined` at that index, it's not detected by the `in` operator. Array iteration methods also ignore them."},{"_id":"66871a195a9b62091c000128","treeId":"6233ffe7781cf6071600010d","seq":6746036,"position":2,"parentId":"667a3de45a9b62091c000112","content":"#### Which Operations Ignore Holes, and Which Consider Them?\n\nArray iteration methods\n\n|Method|Behavior|\n|:-----||\n|`forEach()`|ignores|\n|`every()` |ignores|\n|`map()` |skips but preserves|\n|`filter()` |eliminates|\n\n|Method|Behavior|\n|:-----||\n|`join()`|converts holes, `undefined`, `null` to `''`|\n|`sort()`|preserves while sorting|\n\nFunction.prototype.apply()\n\nWhen `apply()` accepts an otherwise empty array with holes, it turns them to `undefined`.\n\nYou can create an array with undefined as values with `Array.apply`. But `apply` wont' necessarily replace holes with `undefined` in nonempty arrays.\n\n\n"},{"_id":"66872bdd5a9b62091c000129","treeId":"6233ffe7781cf6071600010d","seq":6746039,"position":3,"parentId":"667a3de45a9b62091c000112","content":"#### Removing Holes from Arrays\n\n`filter( )` removes holes.\n\nTo replace holes with `undefined`, use a loop that assigns each array element to itself."},{"_id":"667a3e4a5a9b62091c000113","treeId":"6233ffe7781cf6071600010d","seq":6745887,"position":6,"parentId":"667a29425a9b62091c00010d","content":"### Array Constructor Method\n\nUse `Array.isArray(obj)` instead of `instanceof` to detect Arrays."},{"_id":"667a40695a9b62091c000115","treeId":"6233ffe7781cf6071600010d","seq":6746052,"position":8,"parentId":"667a29425a9b62091c00010d","content":"### Adding and Removing Elements (Destructive)\n\n`Array.prototype.shift()`\n`Array.prototype.unshift(elem1?, elem2?, ...)`\n`Array.prototype.pop()`\n\n`Array.prototype.push(elem1?, elem2?, ...)`\n`Array.prototype.push.apply(thisValue, argArray)`\n\n`Array.prototype.splice(start, deleteCount?, elem1?, elem2?, ...)`\n\n``"},{"_id":"667a40795a9b62091c000116","treeId":"6233ffe7781cf6071600010d","seq":6746063,"position":9,"parentId":"667a29425a9b62091c00010d","content":"### Sorting and Reversing Elements (Destructive)\n\n`Array.prototype.reverse()`\n`Array.prototype.sort(compareFunction?)`\n\nComparison functions should return the following:\n\n|Result |Return Value|\n|:------------|-----------:|\n|less than |`-1`|\n|equal |`0`|\n|greater than |`1`|\n\n**Comparing Numbers**\n\nUse conditional statements. Subtracting can cause overflow.\n\n**Comparing Strings**\n\nUse `String.prototype.localeCompare`"},{"_id":"668748435a9b62091c00012a","treeId":"6233ffe7781cf6071600010d","seq":6746060,"position":1,"parentId":"667a40795a9b62091c000116","content":"#### Comparing Numbers\n\n"},{"_id":"667a40855a9b62091c000117","treeId":"6233ffe7781cf6071600010d","seq":6746065,"position":10,"parentId":"667a29425a9b62091c00010d","content":"### Concatenating, Slicing, Joining (Nondestructive)\n\n`Array.prototype.concat(arr1?, arr2?, ...)`\n\n`Array.prototype.slice(begin?, end?)`\nWill copy the array if no indices are provided.\n\n`Array.prototype.join(separator?)`\nUses `,` as a default separator."},{"_id":"667a40925a9b62091c000118","treeId":"6233ffe7781cf6071600010d","seq":6746066,"position":11,"parentId":"667a29425a9b62091c00010d","content":"### Searching for Values (Nondestructive)\n\n`Array.prototype.indexOf(searchValue, startIndex?)`\nReturns index of first match, or `-1` if not found. Uses strict equality.\n\n`Array.prototype.lastIndexOf(searchElement, startIndex?)`\nSearches from `startIndex` to the beginning of the array."},{"_id":"667a40a25a9b62091c000119","treeId":"6233ffe7781cf6071600010d","seq":6746415,"position":12,"parentId":"667a29425a9b62091c00010d","content":"### Iteration (Nondestructive)\n\nExamination - `forEach( )` `every( )`, `some( )`\n\nTransformation - `map( )` `filter( )`\n\nReduction - `reduce( )` `reduceRight( )`"},{"_id":"668767815a9b62091c00012b","treeId":"6233ffe7781cf6071600010d","seq":6746387,"position":1,"parentId":"667a40a25a9b62091c000119","content":"Examination Methods\n\n`Array.prototype.forEach(callback, thisValue?)` - iterates over all elements. Doesn't support break--use `some( )` instead\n\n`Array.prototype.every(callback, thisValue?)` - `true` if true for every element; stops as soon as it gets `false`\n\n`Array.prototype.some(callback, thisValue?)` - returns `true` if the callback returns `true` for at least one element. Stops iteration once it gets a `true`"},{"_id":"668767a65a9b62091c00012c","treeId":"6233ffe7781cf6071600010d","seq":6746412,"position":2,"parentId":"667a40a25a9b62091c000119","content":"Transformation Methods\n\n```\nfunction callback(element, index, array)\n```\n\n`Array.prototype.map(callback, thisValue?)` - return an array with callback applied to each element\n\n`Array.prototype.filter(callback, thisValue?)` - return a new array containing only elements for which callback returned true"},{"_id":"668767e95a9b62091c00012d","treeId":"6233ffe7781cf6071600010d","seq":6746410,"position":3,"parentId":"667a40a25a9b62091c000119","content":"Reduction Methods\n\n```\nfunction callback(previousValue,\n currentElement, currentIndex, array)\n```\n\n`Array.prototype.reduce(callback, initialValue?)`\n`Array.prototype.reduceRight(callback, initialValue?)`\n\nIf initial value is not provided, `previousValue` is the first element and `currentElement` is the second element."},{"_id":"667a40ad5a9b62091c00011a","treeId":"6233ffe7781cf6071600010d","seq":6745836,"position":13,"parentId":"667a29425a9b62091c00010d","content":"### Best Practices: Iterating over Arrays\n\n1. Use a `for` loop\n2. Use array iteration methods (`forEach()`, `some()`, `every()`, `map()`, `filter()`, `reduce()`, `reduceRight()`)\n\nDon't use `for-in`, since that will iterate over all properties, not elements."},{"_id":"625bef5571800f9971000034","treeId":"6233ffe7781cf6071600010d","seq":6573875,"position":1,"parentId":"625beef671800f9971000033","content":"# Professional: JavaScript for Web Developers\n`Nicholas C. Zakas`"},{"_id":"625bf05e71800f9971000035","treeId":"6233ffe7781cf6071600010d","seq":6754584,"position":1,"parentId":"625bef5571800f9971000034","content":"### 2. JavaScript in HTML - Review Questions\n\n- What are the six attributes for the script element?\n - Which ones are optional, required, or depreciated?\n - Which ones are valid for inline scripts?\n - What does each one do?\n- What is an inline script?\n - What are restricted character strings in an inline script? What's the workaround?\n - How does an inline script affect display/interpretation of the rest of the page content in a browser?\n- What is an external script?\n - What attributes are required for an external script?\n - What is the syntax for an external script?\n - JavaScript files need a `.js` extension?\n- In what order are script elements executed by default?\n - How do `defer` and `async` affect script execution?\n- What was the rationale for putting script elements in the `<head>` part of the document, and what are the drawbacks?\n- Where do modern webapps commonly put script elements, and why?\n- According to the HTML specification, when (in what order & before and after what DOM elements) are deferred scripts executed?\n- How do you specify a `defer` attribute in an XHTML tag?\n- What steps should you take when you embed inline scripts in XHTML documents?\n- When is XHTML mode triggered in a browser?\n- What are the three main arguments for primarily using external files?\n- What document modes exist for most browsers?\n- When is Quirks Mode triggered?\n- What is the difference between Standards Mode and Almost Standards Mode?\n- When is content contained in a `<noscript>` element displayed?"},{"_id":"6361e7fcdc812ae6a900020a","treeId":"6233ffe7781cf6071600010d","seq":6754576,"position":0.5,"parentId":"625bf05e71800f9971000035","content":"### Data Types\n|Data Type |`typeof( )` |Description|\n|:---------|:------------|:----------|\n|Undefined |`'undefined'`|`undefined`; _uninitialized/undeclared variables_|\n|Null |`'object'` |`null`|\n|Boolean |`'boolean'` |`true` `false`|\n|Number |`'number'` |_integers, floating point, +/-`Infinity`, `NaN`_|\n|String |`'string'` |_characters, character literals, empty strings_|\n|Object |`'object'` |JavaScript objects|"},{"_id":"63621df6dc812ae6a900020e","treeId":"6233ffe7781cf6071600010d","seq":6142006,"position":1,"parentId":"6361e7fcdc812ae6a900020a","content":"### Undefined type\n\n- Superficially equal to `null`"},{"_id":"63621f14dc812ae6a900020f","treeId":"6233ffe7781cf6071600010d","seq":6142007,"position":2,"parentId":"6361e7fcdc812ae6a900020a","content":"### Null type\n- Superficially equal to `undefined`"},{"_id":"6362203ddc812ae6a9000210","treeId":"6233ffe7781cf6071600010d","seq":6142023,"position":3,"parentId":"6361e7fcdc812ae6a900020a","content":"### Number\n\nIntegers (dec, octal, hex)\n```\n55\n070\n0xA\n```\n\nFloating Point (IEEE 754)\n```\n301.001\n2.91E23\n```\n\nRange: `Number.MIN_VALUE` `Number.MAX_VALUE`\n\n\n`Infinity` `-Infinity` - can't be used in further calculations. Check with `isFinite( )`.\n\n`NaN` - detect with `isNaN( )`\n\nCast to number type with `Number( )`"},{"_id":"636225ffdc812ae6a9000211","treeId":"6233ffe7781cf6071600010d","seq":6142020,"position":1,"parentId":"6362203ddc812ae6a9000210","content":"#### `isNaN( x )`\n\n- `false` if value can be converted into a number\n- `true` if it cannot\n\nWhen applied to objects, calls `valueOf( )` method."},{"_id":"63622c18dc812ae6a9000212","treeId":"6233ffe7781cf6071600010d","seq":6746029,"position":2,"parentId":"6362203ddc812ae6a9000210","content":"#### `Number( x )`\n\n|Input |Output |\n|----------:|:--------------------|\n|Boolean |`true`->1; `false`->0|\n|Number |(passes through) |\n|`null` |`0` |\n|`undefined`|`NaN` |\n\n\n**Strings**\n\n|String |Output |\n|:----------|:--------------------|\n|numeric strings, no decimal|decimal integer|\n|floating point format|floating point|\n|hex format|hex|\n|empty|`0`|\n|anything else|`NaN`|"},{"_id":"63623aa2dc812ae6a9000213","treeId":"6233ffe7781cf6071600010d","seq":6142063,"position":3,"parentId":"6362203ddc812ae6a9000210","content":"#### `parseInt( x, radix )`\n\nReturns the first contiguous numeral string's numerical value, ignoring the rest of the string."},{"_id":"63623d13dc812ae6a9000214","treeId":"6233ffe7781cf6071600010d","seq":6142064,"position":4,"parentId":"6362203ddc812ae6a9000210","content":"#### `parseFloat( x )`\n\nWill return the value of the the first valid contiguous numerical string in floating point format."},{"_id":"63623f9bdc812ae6a9000215","treeId":"6233ffe7781cf6071600010d","seq":6142076,"position":4,"parentId":"6361e7fcdc812ae6a900020a","content":"### String\n\n_Characters, character strings, character literals._\n\n- Can be enclosed in single `''` or double `\"\"` quotes.\n- Character literals (`\\n\\t\\\\`, unicode, etc) are counted as single characters, not by the number of characters in their ascii escape sequence.\n- Are immutable.\n- Other types can be type cast using `toString( )`"},{"_id":"63624679dc812ae6a9000217","treeId":"6233ffe7781cf6071600010d","seq":6142122,"position":5,"parentId":"6361e7fcdc812ae6a900020a","content":"#### Object\n_JavaScript objects\n\nAll objects have the following methods:\n\n- `hasOwnProperty( prop )`\n- `isPrototypeOf( obj )`\n- `propertyISEnumerable( prop )`\n- `toLocaleString()` - return string representation of object that is appropriate for locale\n- `toString()` - string representation of object\n- `valueOf()` - string, number, or Boolean representation of object"},{"_id":"625bf1cb71800f9971000037","treeId":"6233ffe7781cf6071600010d","seq":5925485,"position":1,"parentId":"625bf05e71800f9971000035","content":""},{"_id":"625c012f71800f9971000038","treeId":"6233ffe7781cf6071600010d","seq":5925585,"position":2,"parentId":"625bef5571800f9971000034","content":"### 3. Language Basics Review Questions\n\n#### Syntax\n\n- JavaScript is specified (syntax, operators, data types, built-ins) in what standard? What is the name of the pseudolanguage description used in the standard?\n- What is the latest standard for JavaScript?\n- What versions of the JavaScript standard do the following engines support? Which one(s) support the most advanced features?\n - Chakra\n - JavaScriptCore (Nitro)\n - JScript 9.0\n - KJS\n - Spider Monkey \n - V8\n- True or false: an identifier in JavaScript that is an uppercase or lowercase version of a reserved word cannot be used.\n- What are valid first characters of an identifier?\n- What are valid subsequent characters for an identifier?\n- What kinds of comments does JavaScript support?"},{"_id":"6361e355dc812ae6a9000209","treeId":"6233ffe7781cf6071600010d","seq":6142390,"position":3,"parentId":"625bef5571800f9971000034","content":"## 3. Language Basics\n\n- Syntax\n- Keywords and Reserved Words\n- Variables\n- Data Types\n- Operators\n- Statements\n- Functions"},{"_id":"6361e855dc812ae6a900020b","treeId":"6233ffe7781cf6071600010d","seq":6142147,"position":2,"parentId":"6361e355dc812ae6a9000209","content":"### Operators\n\n- Unary `+` `-`\n- Increment/Decrement `++` `--`\n- Bitwise `~` `&` `|` `^`\n- Bitwise Shift `<<` `>>` `>>>`\n- Logical (Boolean) `!` `&&` `||`\n- Multiplicative `*` `/` `%`\n- Additive `+` `-`\n- Relational `<` `>` `<=` `>=`\n- Equality `==` `!=` `===` `!===`\n- Assignment `=` `*=` `/=` `+=` `-=` `%=` `<<=` `>>=` `>>>=`\n- Comma `,`"},{"_id":"63708332dc812ae6a9000221","treeId":"6233ffe7781cf6071600010d","seq":6149589,"position":0.5,"parentId":"6361e855dc812ae6a900020b","content":"#### Unary `+` `-`\n\n- `+` does nothing to a number type variable, casts the variable using `Number()`\n- `-` negates a number type variable, and returns the negation of a non-numeric value after its converstion with `Number()`"},{"_id":"63708d0fdc812ae6a9000222","treeId":"6233ffe7781cf6071600010d","seq":6149735,"position":0.75,"parentId":"6361e855dc812ae6a900020b","content":"#### Logical `!` `&&` `||`\n\n|Operand |`!` |\n|:-----------|:-------:|\n|`true` |`false` |\n|`false` |`true` |\n|object |`false` |\n|empty string|`true` |\n|nonempty string|`false`|\n|`0` |`true`|\n|nonzero number|`false`|\n|`null` |`true`|\n|`NaN` |`true`|\n|`undefined |`true`|\n\n`&&` will always short circuit to `false` if the first operand is `false`.\n\n`||` will always short circuit to `true` if the first argument is `true`\n\n|Operand1|Operand2|`&&` |OR |\n|:-------|:-------|:-------:|:--------:|\n|`true` |`true` |`true` |`true` |\n|`true` |`false` |`false` |`true` |\n|`false` | * |short circuit `false`|Operand2|\n|`true` |`false` |`false` |short circuit `true`|\n|Object | * |Operand2 |Operand1|\n| `true` |Object |Operand2 |short circuit `true`|\n|Object |Object |Operand2 |Operand1|\n|`null` | * | `null` |`null` if Operand2===`null`|\n|`NaN` | * | `NaN` |`NaN` if Operand2===`NaN`|\n|`undefined`| * | `undefined`|`undefined` if Operand2===`undefined`|\n|undeclared| * |_error_ |_error_|\n|`true` |undeclared|_error_|short circuit `true`|\n|`false` |undeclared|short circuit `false` |_error_|\n\n"},{"_id":"63625c68dc812ae6a9000218","treeId":"6233ffe7781cf6071600010d","seq":6142155,"position":1,"parentId":"6361e855dc812ae6a900020b","content":"#### Comma\n\nAllows execution of more than one operation in a single statement.\n\nUsually used for variable declaration.\n```\nvar a1=1,\n a2=2,\n a3=3;\n```\n\nWhen used to assign values, returns the last item in the expression.\n```\nvar num = (5, 1, 4, 8, 0); // num = 0\n```"},{"_id":"6361e8a2dc812ae6a900020c","treeId":"6233ffe7781cf6071600010d","seq":6142169,"position":3,"parentId":"6361e355dc812ae6a9000209","content":"### Statements\n\n- if\n- do-while\n- while\n- for\n- for-in\n- break\n- continue\n- with\n- switch"},{"_id":"63626540dc812ae6a900021a","treeId":"6233ffe7781cf6071600010d","seq":6142200,"position":0.5,"parentId":"6361e8a2dc812ae6a900020c","content":"#### Labeled statements\n```\nbutts: for (var i=0; i < count; i++) {\n console.log(i*i);\n}\n```"},{"_id":"6362642fdc812ae6a9000219","treeId":"6233ffe7781cf6071600010d","seq":6142264,"position":1,"parentId":"6361e8a2dc812ae6a900020c","content":"#### break and continue\n\n`break` exits a loop immediately, and the next statement after the loop is executed.\n\n`continue` exits a loop iteration, but execution resumes the beginning of the loop.\n\nYou can specify a labeled statement as the target of `break` or `continue`. This is powerful but can cause debugging problems."},{"_id":"636293d6dc812ae6a900021b","treeId":"6233ffe7781cf6071600010d","seq":6142282,"position":2,"parentId":"6361e8a2dc812ae6a900020c","content":"#### with\n\nNot allowed in strict mode. Don't use in production code.\n\n```\nvar qs = location.search.substring(1);\nvar hostName = location.hostname;\nvar url = location.href;\n```\nis equivalent to:\n```\nwith(location){\n var qs = search.substring(1);\n var hostName = hostname;\n var url = href;\n}\n```"},{"_id":"63629971dc812ae6a900021c","treeId":"6233ffe7781cf6071600010d","seq":6142293,"position":3,"parentId":"6361e8a2dc812ae6a900020c","content":"#### switch\n\nMatches similar to `==`. Works with all data types, including strings and objects. Case values do not need to be constants."},{"_id":"6361e8cfdc812ae6a900020d","treeId":"6233ffe7781cf6071600010d","seq":6142371,"position":4,"parentId":"6361e355dc812ae6a9000209","content":"### Functions\n\n- Can be assigned to variables\n- Always return values. Default value is `undefined`\n- No function signatures\n- No overloading (last declared function overrides previous ones)\n\n#### Strict Mode\n\n- Functions and parameters cannot be named **eval** or **arguments**\n- No named parameters with the same name\n\n#### Arguments\n\n- Acts similar to **argv**\n- Interpreter won't complain if function called with a different number of arguments than the declaration\n- Named parameter not passes in function call is assigned `undefined`\n- `arguments` object: acts like an array, but is not instance of Array\n\n```\nvar beets = function(){\n if (arguments) {\n if (arguments.length >= 3) {\n for (x in arguments) {\n console.log(x);\n }\n } else if (arguments.length === 2) {\n console.log('1. ' + arguments[0]);\n console.log('2. ' + arguments[1]);\n } else {\n console.log('only argument: ' + arguments[0]);\n }\n }\n}\n```\n\nArguments stay in sync with named parameters:\n- Change to named parameter will change corresponding argument\n- Not the other way around"},{"_id":"6362bf1cdc812ae6a900021d","treeId":"6233ffe7781cf6071600010d","seq":6142380,"position":4,"parentId":"625bef5571800f9971000034","content":"## 4. Variables, Scope, and Memory\n\n- Primitive and Reference Values\n- Execution Context and Scope\n- Garbage Collection"},{"_id":"6362c3b8dc812ae6a900021e","treeId":"6233ffe7781cf6071600010d","seq":6160807,"position":1,"parentId":"6362bf1cdc812ae6a900021d","content":"### Primitive and Reference Values\n\nPrimitive values are accessed ***by value***.\n\nObjects are accessed ***by reference***.\n\n#### Dynamic Properties\nYou can add properties to reference values at any time.\nTrying to add properties to primitive values won't work, but also won't cause an error.\n\n#### Copying Values\nAssigning a primitive value creates a new copy.\nAssigning a reference value passes the reference to the same object instance.\n\n#### Argument Passing\nAlways passed by value--value is copied into a local variable. Passing by reference is not possible in JS. This functionality is replaced by closures.\n\n#### Determining Type\n`typeof( )` returns the type of primitive values.\n***variable*** `instanceof` ***Constructor*** returns `true` if X is an instance of reference type with constructor _Constructor_."},{"_id":"6370e22ddc812ae6a9000223","treeId":"6233ffe7781cf6071600010d","seq":6149882,"position":1,"parentId":"6362c3b8dc812ae6a900021e","content":"#### Dynamic Properties"},{"_id":"6370e284dc812ae6a9000224","treeId":"6233ffe7781cf6071600010d","seq":6149883,"position":2,"parentId":"6362c3b8dc812ae6a900021e","content":"#### Copying Values"},{"_id":"6362c466dc812ae6a900021f","treeId":"6233ffe7781cf6071600010d","seq":6161452,"position":2,"parentId":"6362bf1cdc812ae6a900021d","content":"### Execution Context and Scope\n\n**Execution Context** - defines access and behavior for a variable or function--what other data it can access. This is not accessible directly by code.\n\nAn inner context can access variables in an outer context, but not the other way around.\n\nIn web browsers, the **global execution context** is the `window` object. Each function has its own local execution context.\n\nThe other primary type of context is the **function execution context**.\n\n**Scope Chain** provides access to all variables and functions in the execution context.\n\nThe **Variable Object** is the front of the Scope Chain.\n\nIn **Functions** the **Activation Object** is used as the variable object.\n\nEach context can search up the scope chain, but not down.\n\n- **Scope Chain Augmentation** - temporary addition to front of the scope chain, caused by `catch` and `with`\n- **No Block-Level Scopes**"},{"_id":"637cb39bdc812ae6a9000225","treeId":"6233ffe7781cf6071600010d","seq":6161371,"position":1,"parentId":"6362c466dc812ae6a900021f","content":"#### Activation Object of a Function\n\nStarts with `arguments`.\n\nNext variable object is from the containing context.\n\nEach subsequent variable object in the chain is that of the next immediately enclosing scope.\n\nThe last variable object in the chain belongs to the global scope."},{"_id":"637ce042dc812ae6a9000227","treeId":"6233ffe7781cf6071600010d","seq":6161521,"position":3,"parentId":"6362c466dc812ae6a900021f","content":"#### Scope Chain Augmentation\n\nA `catch` block in a ***try-catch** statement and a `with` statement both add a variable object to the front of a scope chain.\n\n***with***\n```\nwith (aThing) {\n /* ... */\n}\n```\n`aThing` is added to the scope chain.\n\n***try-catch***\n```\ntry {\n} catch (e) {\n /* ... */\n}\n```\n\nThe `catch` statement will create a new variable object containing `e`, the error object that was thrown."},{"_id":"637cf3e6dc812ae6a9000228","treeId":"6233ffe7781cf6071600010d","seq":6161581,"position":4,"parentId":"6362c466dc812ae6a900021f","content":"#### No-Block Level Scoping\n\nVariables declared in blocks, such as in `if` statements and in the initialization part of `for` statements are available in the rest of the enclosing function scope."},{"_id":"637cf849dc812ae6a9000229","treeId":"6233ffe7781cf6071600010d","seq":6161596,"position":5,"parentId":"6362c466dc812ae6a900021f","content":"#### Variable Declaration\n\nDeclaring a variable with `var` will add it to the immediate context.\n\n`!` - A variable that gets initialized without being declared gets added to the **global context**: it will continue to exist until execution exits the global scope.\n\nAlways declare variables before initializing this to avoid problems."},{"_id":"637cd03bdc812ae6a9000226","treeId":"6233ffe7781cf6071600010d","seq":6161618,"position":6,"parentId":"6362c466dc812ae6a900021f","content":"#### Resolving Identifiers\n\nIdentifiers get resolved by navigating the scope chain from beginning to end.\n\nA variable is accessible as long as it can be found in the scope chain.\n\nThe search may also search each object's prototype chain.\n\nThe first match in the identifier search gets returned.\n```\nvar name = \"Khyr ad-Din\";\nfunction getName() {\n var name = \"Edmund Harvey\";\n return name;\n}\nconsole.log(getName()); // \"Edmund Harvey\"\n```\nIn this case the **name** variable in the parent context of **getName** can't be accessed."},{"_id":"6362c4f4dc812ae6a9000220","treeId":"6233ffe7781cf6071600010d","seq":6161909,"position":3,"parentId":"6362bf1cdc812ae6a900021d","content":"### Garbage Collection\n\n- **Mark-and-Sweep** - variables flagged in context when entering, flagged as out of context when leaving\n- **Reference Counting** - count references to an object/variable and deallocate when zero. Vulnerable to cyclic references. IE8 and earlier had non-native JS objects (DOM/BOM/COM) that used reference counting.\n- **Performance** - \n- **Managing Memory** - dereferencing global values by setting to `null` helps minimize memory usage"},{"_id":"637d3f52dc812ae6a900022a","treeId":"6233ffe7781cf6071600010d","seq":6161863,"position":1,"parentId":"6362c4f4dc812ae6a9000220","content":"#### Reference Counting\n\nCyclic References Example\n```\nfunction thing() {\n var objA = new Object();\n var objB = new Object();\n\n objA.friend = objB;\n objB.friend = objA;\n}\n```\n\nEven once browsers switched to mark-and-sweep GC, non-native JavaScript objects (COM, DOM, BOM) in IE8 and earlier were still vulnerable to cyclic references because they were still implemented with reference counting.\n\n`!` - Make sure to break the connection between native JS and DOM elements by setting cross-references to `null`."},{"_id":"637d503cdc812ae6a900022b","treeId":"6233ffe7781cf6071600010d","seq":6161897,"position":2,"parentId":"6362c4f4dc812ae6a9000220","content":"#### Performance Issues\n\nIE6 and earlier ran GC when threshold of 256 variable allocations, 4096 object/array literals/array slots, or 64kb of strings was reached.\n\nScripts with a lot of variables/strings kept the GC running really frequency, leading to performance issues.\n\nIE7 instead had dynamic thresholds based on how many allocations were reclaimed per sweep."},{"_id":"6411b906a052abb4760000b5","treeId":"6233ffe7781cf6071600010d","seq":6268752,"position":5,"parentId":"625bef5571800f9971000034","content":"## 5. Reference Types\n\nObjects are instances of a particular ***reference type***. Reference types are also sometimes called _object definitions_.\n\nReference types are not classes. JavaScript does not have classes. A new object instance is created with the `new` operator.\n\n```\nvar butt = new Thing();\n```\n\nECMAScript provides a bunch of built-in reference classes.\n\n- The Object Type\n- The Array Type\n- The Date Type\n- The Regexp Type\n- The Function Type\n- Primitive Wrapper Types\n- Singleton Built-In Objects"},{"_id":"6411d437a052abb4760000bb","treeId":"6233ffe7781cf6071600010d","seq":6268824,"position":0.0625,"parentId":"6411b906a052abb4760000b5","content":"### The Object Type\n\nTwo ways to create an Object instance explicitly\n\nObject literal notation, and when it is used\n\nExpression context, statement context, how context affects interpretation of `{`\n\nProperty names in object literal notation\n\nCreating an empty object\n\nWay to access object properties\n\nWhen bracket notation is favored\n"},{"_id":"6411d133a052abb4760000ba","treeId":"6233ffe7781cf6071600010d","seq":6303610,"position":0.125,"parentId":"6411b906a052abb4760000b5","content":"### The Array Type\n\nArrays can hold any data type at any index. (They are more similar to lists in Python than Arrays in Java.)\n\nThere are two main ways to create arrays: the **Array constructor** and an **Array literal**.\n\nArray elements are accessed via index and square bracket.\n\n```\nben[1] = \"helicopter\";\n```\n\nThe number of elements in an array is given by the `length` property.\n\nThe length property is mutable: decreasing `length` truncates elements from the end of the Array. Increasing `length` appends elements with the value of `undefined` to the end of the array.\n\n```\ncolors[colors.length] = \"butt brown\"; // appends value to end of array\n```\n\n- Detecting Arrays\n- Conversion Methods\n- Stack/Queue Methods\n- Reordering Methods\n- Manipulation Methods\n- Location Methods\n- Iterative Methods\n- Reduction Methods"},{"_id":"641219cda052abb4760000bd","treeId":"6233ffe7781cf6071600010d","seq":6278328,"position":1,"parentId":"6411d133a052abb4760000ba","content":"### Creating Arrays, best practices\n\nThere are two main ways to create an array:\n\n#### 1. Array constructor\n\n#### 2. Array literal\n```\nvar anEmptyArray = []; // creates an empty array\nvar numbersAgain = [1,2,]; // don't do this\nvar numbersOrWhat = [,,,,,] // don't do this either\n```\n\nCreating empty arrays with commas, or leaving the last element blank causes inconsistent behavior. In IE8 and earlier, the last, hanging comma will create an additional index with the value `undefined` (this is a bug). Other browsers will not create an additional index giving a hanging comma.\n\nArray literal notation doesn't call the `Array()` constructor except in Firefox 2.x and earlier."},{"_id":"64121b92a052abb4760000be","treeId":"6233ffe7781cf6071600010d","seq":6278331,"position":2,"parentId":"6411d133a052abb4760000ba","content":"#### Detecting Arrays\n\n`x instanceof Array` will not correctly identify `x` as an Array if it was passed from a different frame or page, and `x`'s array type has a different constructor.\n\nInstead, ECMAScript 5 provides `Array.isArray( anObject )` to detect arrays.\n\n"},{"_id":"641255baa052abb4760000bf","treeId":"6233ffe7781cf6071600010d","seq":6278374,"position":3,"parentId":"6411d133a052abb4760000ba","content":"#### Conversion Methods\n\n`.toString()` `.valueOf()`\n\nReturns a comma delimited list of each element's `.toString()` values.\n\n`.toLocaleString()`\n\nReturns a comma delimited list of each element's `.toLocaleString()` values.\n\n`.join(sep)`\n\nReturns a list separated by the string specified by `sep`.\n\nIf `sep` is not provided or undefined, it uses a comma. IE 7 and before has a bug that uses `undefined` as the delimiter."},{"_id":"641270b3a052abb4760000c6","treeId":"6233ffe7781cf6071600010d","seq":6278378,"position":3.5,"parentId":"6411d133a052abb4760000ba","content":"#### Stack Methods\n\n`push(itemTachi, ...)`\n\nAppends any number of elements to the _end_ of an array.\n\n`pop()`\n\nReturns the last element of the array and decrements the `length` property."},{"_id":"6412560ea052abb4760000c0","treeId":"6233ffe7781cf6071600010d","seq":6268988,"position":4,"parentId":"6411d133a052abb4760000ba","content":"#### Queue Methods\n\n`shift()`\n\nReturns the first element of the array removes it from the array (_shifting_ all the indicies downward).\n\n`unshift(elemTachi, ...)`\n\nPrepends any number of elements to an array."},{"_id":"64125676a052abb4760000c1","treeId":"6233ffe7781cf6071600010d","seq":6278394,"position":5,"parentId":"6411d133a052abb4760000ba","content":"#### Reordering Methods\n\n`.reverse()` - reverses the elements in the array.\n\n`.sort( comparator )`\n\nSorts the elements of the array based on a comparison function. For each pair of elements in an array, the comparison function should basically do this:\n\n```\nfunction comparator(v1, v2) {\n if ( /* v1 < v2 */) {\n return -1;\n } else if (/* v1 > v2 */) {\n return 1;\n } else {\n return 0;\n }\n}\n```\n\nIf no comparison function is provided, `sort()` **will return the elements in sorted in ascending order of their `String()` values by default**."},{"_id":"641256bda052abb4760000c2","treeId":"6233ffe7781cf6071600010d","seq":6278446,"position":6,"parentId":"6411d133a052abb4760000ba","content":"#### Manipulation Methods\n\n`.concat( elementsOrArraysTachi, ... )`\n\nReturns a new array with specified elements appended to the end of the original array. Will append the _elements_ of any arrays passed into it. If no elements or arrays are passed in, it will clone the original array.\n\n`.slice( startIndex, stopIndex )`\n\nReturns a new array containing elements between `startIndex` and up to but not including `stopIndex`. `stopIndex` is optional and if it is not specified, `slice( )` will just return elements from startIndex up to the end of the array.\n\n`.splice(startIndex, replaceCount, elem[,...] )`\n\nSplice can delete, insert, or replace items in the middle (or at any point) of an array.\n\nDeletion - specify two arguments: `startIndex` is the first item to delete, and `replaceCount` is the number elements to delete.\n\nInsertion - specify three or more arguments: `startIndex` is the insertion point, have replaceCount=0, and then specify any number of elements to insert.\n\nReplacement - specify three or more arguments: `startIndex` is the replacement point, `replaceCount` is the number of elements to delete, and elem[...] are the items to insert."},{"_id":"64125748a052abb4760000c3","treeId":"6233ffe7781cf6071600010d","seq":6278450,"position":7,"parentId":"6411d133a052abb4760000ba","content":"#### Location Methods\n\nEach of these uses the `===` operator to find a match:\n\n`.indexOf()`\n\n`.lastIndexOf()`\n"},{"_id":"6412579ca052abb4760000c4","treeId":"6233ffe7781cf6071600010d","seq":6303620,"position":8,"parentId":"6411d133a052abb4760000ba","content":"#### Iterative Methods\n\nLet `f( )` be a function that takes the following arguments (all optional):\n\n```\nfunction f(elem, i, array)\n```\n\nEach of the following methods run `f( )` for each element in the array. The current element is passed as `elem`, the index as `i`, and the array itself as `array`.\n\n|Method|return value|\n|------|------------|\n|`.every(f)`| `true` if `f( )` returns true for every element in the array, `false` otherwise|\n|`.filter(f)`| array of all items for which `f( )` returns `true`|\n|`.forEach(f)`| no return value|\n|`.map(f)`|result of each call to `f( )`, as an array|\n|`.some(f)`|`true` if `f( )` returns true for any item|"},{"_id":"641257e0a052abb4760000c5","treeId":"6233ffe7781cf6071600010d","seq":6278530,"position":9,"parentId":"6411d133a052abb4760000ba","content":"#### Reduction Methods\n\n`.reduce(f, iv)` `.reduceRight(f, iv)`\n\nIterates through all elements of an array, either from the first element (`reduce`) or from the last element `reduceRight`.\n\n```\nfunction f(prev, cur, index, theArray) {\n /* ... */\n return val;\n}\n```\n`iv` (optional) is passed in as prev on the first iteration (when cur is set to element 0).\n\nThe return value of the function (`val` in f) is passed in as `prev` on the next iteration.\n\ne.g. sequences, series, iterative algorithms"},{"_id":"6411cfada052abb4760000b9","treeId":"6233ffe7781cf6071600010d","seq":6286130,"position":0.25,"parentId":"6411b906a052abb4760000b5","content":"### The Date Type\n\nECMAScript `Date` represents dates as the number of milliseconds since midnight 1970-01-01 UTC.\n\nCreate a new Date object with the `new` operator and the `Date()` constructor.\n\nWithout arguments, the object is set to the current date and time.\n```\nvar now = new Date();\n```\n\n**Reference type methods**\n\n`Date.parse( dateString )`\n\nParses strings containing a date, returning the **UTC date** in milliseconds. The `Date( )` constructor calls `parse( )` if passed a string. Supports several formats as defined by ECMA-262 Fifth Ed.:\n\n- `mm/dd/yyyy`\n- `Month_name dd, yyyy`\n- `Day_of_week Month_name dd yyyy hh:mm:ss Time_zone`\n- `yyyy-mm-ddThh:mm:ss.sssZ` (ECMAScript 5 compliant implementations only)\n\nReturns `NaN` if the string can't be parsed as a date (this happens when the date string doesn't exactly match one of the supported patterns.)\n\n`Date.UTC( y, m[, d, h, m, s, ms] )`\n\nReturns the **local timezone's** date in milliseconds for a specified UTC year, month, day, hour, minute, seconds, and milliseconds.\n\n[ ] Inherited Methods\n[ ] Date-Formatting Methods\n[ ] Date/Time Component Methods"},{"_id":"6411cd3ea052abb4760000b8","treeId":"6233ffe7781cf6071600010d","seq":6286179,"position":0.5,"parentId":"6411b906a052abb4760000b5","content":"### The Regexp Type\n\nRegular Expression literal:\n\n```\nvar exp = /{pattern}/{flags}\n```\n\nSupported flags:\n\n- `g` : global\n- `i` : case insensitive\n- `m` : multiline\n\n**RegEx Metacharacters**\n```\n( [ { \\ ^ $ | ) ] } ? * + .\n```\n\nMetacharacters need to be escaped with `\\` if they are part of the pattern.\n\n**RegEx Constructor**\n```\nvar expression = /\\$\\( +\\)\\./gm;\nvar equivExpression = new RegEx(\"\\\\$\\\\( +\\\\)\\\\.\",\"gm\");\n```\n\nNote how metacharacters need to be double-escaped in the string.\n\n**Differences between literal and constructor creation patterns**\n\nIn ECMAScript versions before 5, regular expression created as a literal will always reference the same RegExp instance (the instance properties remain in the same state.)\n\nA regular expression created with a constructor will always create a new RegEx instance.\n\nIn ECMAScript 5, the literal pattern creates a new instance, like the RegEx constructor.\n\n[ ] RegExp Instance Properties `global` `ignoreCase` `lastIndex` `multiline` `source` `$1 ... $9`\n[ ] RegExp Instance Methods `exec( )` `test( )` `toLocaleString()` `toString()`\n[ ] RegExp Constructor Properties\n\n```\ninput $_\nlastMatch $&\nlastParen $+\nleftContext $`\nmultiline $*\nrightContext $'\n```\n \n[ ] Pattern Limitations"},{"_id":"6411c9f1a052abb4760000b7","treeId":"6233ffe7781cf6071600010d","seq":6287215,"position":1,"parentId":"6411b906a052abb4760000b5","content":"### The Function Type\n\nThere are three main ways to define a function:\n\n##### Function-Declaration Syntax\n```\nfunction f(args, bargs, dargs) {\n}\n```\n\n##### Function Expression\n```\nvar f = function(args, bargs, dargs){\n};\n```\n\nNote the need of a semicolon, since this is an expression and not a code block.\n\n##### Function Constructor\n```\nvar f = new Function('args', bargs', 'return args+bargs\"); \n```\n\nDon't use this. It causes double interpretation of code.\n\n***Function names are pointers to function objects.***\n\nThis is why there is no overloading--declaring two functions with the same name just overwrites the earlier one with the later one.\n\n- Function Declarations versus Function Expressions\n- Functions as Values\n- Function Internals\n- Function Properties and Methods"},{"_id":"641ddb8a409fbf208e000069","treeId":"6233ffe7781cf6071600010d","seq":6287219,"position":2,"parentId":"6411c9f1a052abb4760000b7","content":"#### Function Declarations versus Function Expressions\n\nFunction Declarations are available in an execution context before any code is executed. This is called **function declaration hoisting**. The engine takes any Javascript function it finds and brings it to the top of the source tree.\n\nFunction Expressions aren't available until the line of code (usually assigning a function to a variable) gets executed. If a function gets called before it's assigned in a function expression, it will cause an \"unidentified identifier\" error."},{"_id":"641ddc3d409fbf208e00006a","treeId":"6233ffe7781cf6071600010d","seq":6287221,"position":3,"parentId":"6411c9f1a052abb4760000b7","content":"#### Functions as Values\n\nFunctions can be used any place any other value can be used.\n\nIt's possible to:\n- Pass a function into another function\n- Return a function as a result of another function\n\nThis is important--you can use this to create a comparison function to use with `sort()` that knows what properties of objects to compare."},{"_id":"641ddc78409fbf208e00006b","treeId":"6233ffe7781cf6071600010d","seq":6287262,"position":4,"parentId":"6411c9f1a052abb4760000b7","content":"#### Function Internals\n\nA function contains three special objects:\n\n`arguments` - Contains arguments passed to the function and a property `callee` which is a pointer to the function that owns the arguments object. This can be important for decoupling arguments from the function's label, such as in recursive functions.\n\n- Strict mode: trying to access `arguments.callee` results in an error.\n- ECMAScript 5 also has `arguments.caller`. Accessing `arguments.caller` in strict mode causes an error. \n\n_Example: write a recursive function (recursive merge sort, factorial) that still works even the name of the function gets changed._\n\n`this` - a reference to the context object the function is operating on. The value of `this` is not determined until the function is called. It is set to the global context by default.\n\n- Strict mode: when a function is called without a context object, `this` is set to undefined unless `apply()` or `call()` are used.\n\n_Example: write a function that uses `this` to produce different output depending on the object that is the context (e.g. window vs. an object)._\n\n`caller` - (ECMAScript 5) contains a reference to the calling function, or `null` if the function was called in the global scope.\n\n- Strict mode: trying to assign a value to `caller` causes an error."},{"_id":"641ddcb5409fbf208e00006c","treeId":"6233ffe7781cf6071600010d","seq":6287218,"position":5,"parentId":"6411c9f1a052abb4760000b7","content":"#### Function Properties and Methods\n\n**Properties**\n\n`length` - the number of named arguments that the function expects\n\n`prototype` - prototype for reference types. Not enumerable in ECMAScript 5.\n\n**Methods**\n\n`apply(valueOfThis, argsArray)` `call(valueOfThis, arg1[,...] )`\n\nExecute the function with a particular `this` context. `apply` accepts an array of arguments (either an Array type or the `arguments` object) and `call` accepts any number of arguments directly.\n\n```\nwindow.color = \"red\";\nvar o = { color: \"blue\" };\n\nfunction sayColor() {\n console.log(this.color);\n}\n\nsayColor(); // red\nsayColor.call(this); // red\nsayColor.call(window); // red\nsayColor.call(o); // blue\n```\n\n`bind(thisValue)` _(ECMAScript 5)_\n\nCreates a new function object _instance_ with the `this` value set to the specified value.\n\n```\nwindow.color = \"Aquamarine\";\nvar o = { color: \"CornflowerBlue\" };\n\nfunction sayColor() {\n console.log(this.color);\n}\nvar objectSayColor = sayColor.bind(o);\nobjectSayColor(); // CornflowerBlue\n```\n\n`toString()` `toLocaleString()`\n\nReturns the function's code."},{"_id":"642beca4409fbf208e000071","treeId":"6233ffe7781cf6071600010d","seq":6287278,"position":1,"parentId":"641ddcb5409fbf208e00006c","content":"Trivia: `bind(con)` will keep the new function bound to `con` even when you attempt to use `apply` or `call` with a different context!"},{"_id":"641e3786409fbf208e00006d","treeId":"6233ffe7781cf6071600010d","seq":6279471,"position":2,"parentId":"6411b906a052abb4760000b5","content":"### Primitive Wrapper Types\n\nAllows primitive values to be treated as objects with methods.\n\nWhen a boolean, number, or string primitive value is accessed in ***read mode*** and a method is called, the following steps occur:\n\n1. Create instance of wrapper type\n2. Call method on instance\n3. Destroy instance\n\nAutomatically created primitive wrapper types are destroyed immediately after use. This means that you cannot add properties or new methods to primitive types.\n\nPrimitive wrappers can be explicitly created with constructors, but this should only be done in rare need. Any values created with the `new` operator and constructor will return typeof \"object\".\n\nThe Object constructor can return an instance of a primitive wrapper by passing in the primitive.\n```\nvar obj = new Object(\"a blah\");\nconsole.log(obj instanceof String); // true\n```\n\n- The Boolean Wrapper Type\n- The Number Wrapper Type\n- The String Wrapper Type"},{"_id":"641e4f2e409fbf208e00006e","treeId":"6233ffe7781cf6071600010d","seq":6279485,"position":1,"parentId":"641e3786409fbf208e00006d","content":"#### The Boolean Wrapper Type\n\n`valueOf()` - Returns `true` or `false`\n\n`toString()` `toLocaleString()` - Returns `'true'` or `'false'` (string values)\n\nDon't use Boolean types in boolean expressions! They are treated and evaluated as objects."},{"_id":"641e4f7c409fbf208e00006f","treeId":"6233ffe7781cf6071600010d","seq":6279506,"position":2,"parentId":"641e3786409fbf208e00006d","content":"#### The Number Wrapper Type\n\n`valueOf()` - Returns the primitive numeric value.\n\n`toString()` `toLocaleString()` - Return the string representation of the numeric value.\n\n`toFixed(places)` - string representation of a number with a specified number of decimal points, rounded.\n\nRounding is bugged in IE 8 and earlier: it rounds numbers in `(-0.94,-0.5]` `[0.5,0.94)` when precision is `0`. It will round numbers in these ranges to `0` when they should be rounded to `1` or `-1`.\n\n`toExponential(places)` - string representation in e-notation.\n```\nvar num = 10;\nconsole.log(num.toExponential(1)); // '1.0e+1'\n```\n\n`toPrecision(precision)` - returns string representation of number in either fixed or exponential notation with `precision` number of digits, rounding when appropriate. Can typically represent numbers with 1 through 21 decimal places."},{"_id":"641e4ff6409fbf208e000070","treeId":"6233ffe7781cf6071600010d","seq":6294715,"position":3,"parentId":"641e3786409fbf208e00006d","content":"#### The String Wrapper Type\n\n**String Character Methods**\n\n`charAt(i)` - returns character at position in string\n\n`charCodeAt(i)` - returns character code at position in string\n\nECMAScript 5 allows bracket notation.\n```\nvar s = \"My Butt\";\nconsole.log(s[3]); // 'B'\n```\n\n**String-Manipulation Methods**\n\n`concat( )` - return concatenation of one or more strings\n\n`slice(startPos, stopPos)`\n\n- Negative arguments treated as `length`+arg.\n\n`substring(startPos, stopPos)`\n\n- Negative arguments converted to `0`.\n\n`substr(startPos, count)`\n\n- Negative startPos treated as `length`+arg.\n- Negative count converted to `0`.\n\n**String Location Methods**\n\n`indexOf(s)`\n`lastIndexOf(s)`\n\n**The `trim()` Method**\n\n`trim()` - Returns a copy of a string with leading and trailing white space removed.\n\n`trimLeft()` `trimRight()` - Nonstandard methods supported in Firefox 3.5+, Safari 5+, Chrome 8+.\n\n**String Case Methods**\n`toLowerCase()` `toLocaleLowerCase()`\n`toUpperCase()` `toLocaleUpperCase()`\n\n**String Pattern Matching Methods**\n`match( regEx )` - returns an array where the first element is the string that matches the entire pattern, and then capturing groups\n\n`search( regEx )` - returns index of substring matching regular expression or `-1` if not found\n\n`replace( searchText, r )` - matches based on a regular expression or a string. `r` can be string or a function. If `r` is a string, it supports special codes for replacement text. If `r` is a function, it gets passed three arguments: the string match, the position of the match, and the whole string. Additional capturing groups can get passed in as an argument. The only way to replace all occurrences is to pass in a RegEx type with the `g` flag set.\n\n- When `r` is a string, you can insert regular expression operation values. (See table).\n\n`split(sep, arrayLimit)` - separates a string into an array of substrings based on separator `sep`, which may be a string or RegEx\n\n- Capturing group behavior differs widely across browsers\n- IE8 and earlier ignore capturing groups\n- Firefox 3.6 includes empty strings in the results array when a capturing group has no match\n\n`localeCompare(s)` - comparator method that returns different values based on whether a string comes before another alphabetically (return values vary slightly by implementation)\n\n- before s: negative number (usually `-1`)\n- equal to s: `0`\n- after s: positive number (usually `1`)\n\n`String.fromCharCode( num[,...], )` - creates a string from character codes"},{"_id":"642bfae2409fbf208e000072","treeId":"6233ffe7781cf6071600010d","seq":6287284,"position":1,"parentId":"641e4ff6409fbf208e000070","content":"#### String Type Trivia\n\n- `concat( )` will convert any non-string type into a string. For example, an Array `['a', 'b']` will be converted to `'a,b'`"},{"_id":"642c0c1e409fbf208e000073","treeId":"6233ffe7781cf6071600010d","seq":6287306,"position":2,"parentId":"641e4ff6409fbf208e000070","content":"`replace( )` character sequences\n\n|Sequence|Replacement Text|\n|--------|----------------|\n|`$$`|$|\n|`$&`|Substring matching entire pattern|\n|`$'`|Right context|\n|$`|Left context|\n|`$n`| _n_ th capture (0-9)|\n|`$nn`|_nn_ th capture (01-99)|"},{"_id":"6446e2d193c1c9c1b1000074","treeId":"6233ffe7781cf6071600010d","seq":6303504,"position":3,"parentId":"6411b906a052abb4760000b5","content":"### Singleton Built-In Objects\n\n- Global object\n- URI-encoding methods\n- `eval()`\n- `Math`"},{"_id":"644721e593c1c9c1b1000075","treeId":"6233ffe7781cf6071600010d","seq":6303499,"position":1,"parentId":"6446e2d193c1c9c1b1000074","content":"#### Global object\n\nProperties\n`undefined` `NaN` `Infinity` `Object` `Array` `Function` `Boolean` `String` `Number` `Date` `RegExp` `Error` `EvalError` `RangeError` `ReferenceError` `SyntaxError` `TypeError` `URIError`\n\nWindow Object\n\nIn browsers, the `window` object acts as the global object't delegate, and it gets all the variables and functions declared in the global scope."},{"_id":"6447220893c1c9c1b1000076","treeId":"6233ffe7781cf6071600010d","seq":6303500,"position":2,"parentId":"6446e2d193c1c9c1b1000074","content":"#### URI-Encoding Methods\n\n`encodeURI(s)` - encodes a string into a valid URI. Meant to be used on an entire URI, so does not encode valid URI components, such as colons, forward slashes, question marks, and percent signs.\n\n`encodeURIComponent(s)` - encodes all nonstandard characters\n\n`decodeURI(s)` - decodes the characters of a URI into a string. Only decodes characters that would have been replaced by `encodeURI()`\n\n`decodeURIComponents(s)` - decodes a URI into a string"},{"_id":"6447222993c1c9c1b1000077","treeId":"6233ffe7781cf6071600010d","seq":6303501,"position":3,"parentId":"6446e2d193c1c9c1b1000074","content":"#### The `eval()` method\n\n- Strict Mode: variables and functions created in eval are not accessible outside."},{"_id":"6447224693c1c9c1b1000078","treeId":"6233ffe7781cf6071600010d","seq":6303502,"position":4,"parentId":"6446e2d193c1c9c1b1000074","content":"### `Math` Object\n\nProperties (constants)\n\n`Math.E`\n`MathLN10`\n`Math.LN2`\n`Math.LOG2E` - base 2 log of e\n`Math.LOG10E` - base 10 log of e\n`Math.PI`\n`Math.SQRT1_2` - square root of 1/2\n`Math.SQRT2`\n\nMethods\n\n`Math.min(x1[, ...] )` - returns the smallest number in a group of numbers. Accepts any number of parameters.\n\n`Math.max(x1[, ...] )` - returns the largest number in a group of numbers.\n\n`Math.ceil(x)` - ceiling function\n\n`Math.floor(x)` - floor function\n\n`Math.round(x)` - rounds number up if decimal component is >= 0.5, or down if not.\n\n`Math.random()` - generates a random number in (0,1)\n\nOther methods:\n\n`Math.abs(x)`\n`Math.exp(x)` - e^x\n`Math.log(x)`\n`Math.pow(x, t) - x^t\n`Math.sqrt(x)`\n`Math.acos(x)` - arc cosine of x\n`Math.asin(x)` - arc sine of x\n`Math.atan(x)` - arc tan of x\n`Math.atan2(y,x)` - arc tangent of y/x\n`Math.cos(x)` - cosine x\n`Math.sin(x)` - sine x\n`Math.tan(x)` - tan x\n\nThe precision of results may vary from implementation to implementation."},{"_id":"6492e6131813ee81b5000095","treeId":"6233ffe7781cf6071600010d","seq":6362835,"position":6,"parentId":"625bef5571800f9971000034","content":"## 6. Object-Oriented Programming"},{"_id":"6492eef81813ee81b5000096","treeId":"6233ffe7781cf6071600010d","seq":6541751,"position":1,"parentId":"6492e6131813ee81b5000095","content":"### Understanding Objects\n\n- Types of Properties\n- Defining Multiple Properties\n- Reading Property Attributes"},{"_id":"65653ff354301f145300011b","treeId":"6233ffe7781cf6071600010d","seq":6541834,"position":1,"parentId":"6492eef81813ee81b5000096","content":"### Types of Properties\n\nData properties and Accessor properties are the two types of properties in JavaScript.\n\n**Data Properties** - single location for a data value\n\n**Accessor Properties** - combination of getter/setter functions\n\n"},{"_id":"65655a6d54301f145300011c","treeId":"6233ffe7781cf6071600010d","seq":6541879,"position":1,"parentId":"65653ff354301f145300011b","content":"Data Properties\n\nAttributes\n\n`[[Configurable]]`\n`[[Enumerable]]`\n`[[Writable]]`\n`[[Value]]`"},{"_id":"6492ef321813ee81b5000097","treeId":"6233ffe7781cf6071600010d","seq":6362839,"position":2,"parentId":"6492e6131813ee81b5000095","content":"### Object Creation\n\n- The Factory Pattern\n- The Constructor Pattern\n- The Prototype Pattern\n- Combination Constructor/Prototype Pattern\n- Dynamic Prototype Pattern\n- Parasitic Constructor Pattern\n- Durable Constructor Pattern"},{"_id":"6492f2e61813ee81b5000098","treeId":"6233ffe7781cf6071600010d","seq":6362841,"position":3,"parentId":"6492e6131813ee81b5000095","content":"### Inheritance\n\n- Prototype Chaining\n- Constructor Stealing\n- Combination Inheritance\n- Parasitic Inheritance\n- Parasitic Combination Inheritance"},{"_id":"675999e2a6afb26c7800017f","treeId":"6233ffe7781cf6071600010d","seq":7126652,"position":2,"parentId":"625beef671800f9971000033","content":"Notes\n\nFunction expressions are not hoisted, so order matters!\n\nThe return value of a constructor will be the value returned when called by `new`"},{"_id":"6b10f73ba8955d05d9000237","treeId":"6233ffe7781cf6071600010d","seq":7864552,"position":3.5,"parentId":null,"content":"# R"},{"_id":"6b10f762a8955d05d9000238","treeId":"6233ffe7781cf6071600010d","seq":7864580,"position":1,"parentId":"6b10f73ba8955d05d9000237","content":"## `swirl` : R Programming"},{"_id":"6b10f7e4a8955d05d9000239","treeId":"6233ffe7781cf6071600010d","seq":7864554,"position":1,"parentId":"6b10f762a8955d05d9000238","content":"### Basic Building Blocks"},{"_id":"6b10f84ea8955d05d900023a","treeId":"6233ffe7781cf6071600010d","seq":7864578,"position":2,"parentId":"6b10f762a8955d05d9000238","content":"### Workspace and Files\n\n`getwd`\n`setwd`\n`list.files` / `dir`\n`args`\n`dir.create`\n`file.create`\n`file.exists`\n`file.info`\n`file.rename`\n`file.copy`\n`file.path`\n`dir.create`\n`unlink`\n"},{"_id":"5781b286fbb01550203a4357","treeId":"6233ffe7781cf6071600010d","seq":7864665,"position":3,"parentId":"6b10f762a8955d05d9000238","content":"### Sequences of Numbers\n\n`?`\n`:`\n`length`\n`seq`\n`seq(along.with = ... )`\n`seq_along`\n`rep(n, times = ..., each = ...)`"},{"_id":"6b11243fa8955d05d900034b","treeId":"6233ffe7781cf6071600010d","seq":7864692,"position":4,"parentId":"6b10f762a8955d05d9000238","content":"### 4. Vectors"},{"_id":"6b112496a8955d05d900034c","treeId":"6233ffe7781cf6071600010d","seq":7872946,"position":5,"parentId":"6b10f762a8955d05d9000238","content":"### 5. Missing Values\n\n`NA`\n`NaN`\n`is.na`\n`rnorm`\n`rep`\n`sample`"},{"_id":"6b1124d3a8955d05d900034d","treeId":"6233ffe7781cf6071600010d","seq":7873056,"position":6,"parentId":"6b10f762a8955d05d9000238","content":"### 6. Subsetting Vectors\n\n```\nx[is.na(x)]\nx[-2]\nx[c(-2,-10)]\nx[-c(2,10)]\nvect <- c(foo = 11, bar = 2, norf = NA)\nnames(vect)\nvect2 <- c(11, 2, NA)\nnames(vect) <- c(\"foo\", \"bar\", \"norf\")\nidentical(vect, vect2)\nvect[\"bar\"]\nvect[c(\"foo\", \"bar\")]\n```"},{"_id":"6b112532a8955d05d900034e","treeId":"6233ffe7781cf6071600010d","seq":7874068,"position":7,"parentId":"6b10f762a8955d05d9000238","content":"### 7. Matrices and Data Frames\n```\nmy_vector <- 1:20\ndim(my_vector)\nlength(my_vector)\ndim(my_vector) <- c(4,5)\nattributes(my_vector)\nclass(my_vector)\nmy_matrix2 <- matrix(1:20, nrow = 4, ncol = 5)\npatients <- c(\"Bill\", \"Gina\", \"Kelly\", \"Sean\")\ncbind(patients, my_matrix)\nmy_data <- data.frame(patients, my_matrix)\ncnames <- c(\"patient\", \"age\", \"weight\", \"bp\", \"rating\", \"test\")\ncolnames(my_data) <- cnames\n```"},{"_id":"6b1125aca8955d05d900034f","treeId":"6233ffe7781cf6071600010d","seq":7864673,"position":8,"parentId":"6b10f762a8955d05d9000238","content":"### 8. Logic"},{"_id":"6b1125f8a8955d05d9000350","treeId":"6233ffe7781cf6071600010d","seq":7864675,"position":9,"parentId":"6b10f762a8955d05d9000238","content":"### 9. Functions"},{"_id":"6b112635a8955d05d9000351","treeId":"6233ffe7781cf6071600010d","seq":7864679,"position":10,"parentId":"6b10f762a8955d05d9000238","content":"### 10. `lapply` and `sapply`"},{"_id":"6b1126c3a8955d05d9000352","treeId":"6233ffe7781cf6071600010d","seq":7864681,"position":11,"parentId":"6b10f762a8955d05d9000238","content":"### 11. `vapply` and `tapply`"},{"_id":"6b112748a8955d05d9000353","treeId":"6233ffe7781cf6071600010d","seq":7864683,"position":12,"parentId":"6b10f762a8955d05d9000238","content":"### 12. Looking at Data"},{"_id":"6b1127b0a8955d05d9000354","treeId":"6233ffe7781cf6071600010d","seq":7864685,"position":13,"parentId":"6b10f762a8955d05d9000238","content":"### 13. Simulation"},{"_id":"6b1127f8a8955d05d9000355","treeId":"6233ffe7781cf6071600010d","seq":7864686,"position":14,"parentId":"6b10f762a8955d05d9000238","content":"### 14. Dates and Times"},{"_id":"6b11284ca8955d05d9000356","treeId":"6233ffe7781cf6071600010d","seq":7864688,"position":15,"parentId":"6b10f762a8955d05d9000238","content":"### 15. Base Graphics"},{"_id":"64e5630713824208b9000096","treeId":"6233ffe7781cf6071600010d","seq":6438140,"position":4,"parentId":null,"content":"# Software Development"},{"_id":"64e5634513824208b9000097","treeId":"6233ffe7781cf6071600010d","seq":6438141,"position":5,"parentId":null,"content":"## Requirements Checklist"},{"_id":"64e563b513824208b9000098","treeId":"6233ffe7781cf6071600010d","seq":6438143,"position":1,"parentId":"64e5634513824208b9000097","content":"Functional Requirements\n[ ] Inputs\n[ ] Outputs\n[ ] External (hard|soft)ware interfaces\n[ ] External communication interfaces"},{"_id":"64e5640913824208b9000099","treeId":"6233ffe7781cf6071600010d","seq":6438144,"position":2,"parentId":"64e5634513824208b9000097","content":"Quality Requirements\n[ ] Expected response time\n[ ] Timing considerations (processing time, data rate, throughput)\n[ ] Security\n[ ] Reliability (crashes, error detection)\n[ ] Hardware requirements\n[ ] Platform requirements\n[ ] Definition of success/failure"},{"_id":"64e5642f13824208b900009a","treeId":"6233ffe7781cf6071600010d","seq":6438145,"position":3,"parentId":"64e5634513824208b9000097","content":"Requirements Quality\n[ ] Requirements in user language\n[ ] No mutual conflict between requirements\n[ ] Tradeoffs for competing attributes\n[ ] Requirements don't specify the design\n[ ] Consistent level of detail\n[ ] Clear enough to turn over for construction\n[ ] Relevant to problem and solution\n[ ] Testable\n[ ] Possible changes and likelihood of change specified"},{"_id":"64e5645413824208b900009b","treeId":"6233ffe7781cf6071600010d","seq":6438146,"position":4,"parentId":"64e5634513824208b9000097","content":"Completeness\n[ ] Areas of incomplete information\n[ ] Satisfying requirements is sufficient for acceptable product\n[ ] Are you comfortable with all the requirements?"}],"tree":{"_id":"6233ffe7781cf6071600010d","name":"Programming Language Notes","publicUrl":"oli-programming-language-notes"}}