Eloquent JavaScript – Chapter 1: Values, Types, and Operators; Rough Notes

  • Data is stored as bits – any kind of two-valued things
  • Bits – usually described as zeros and ones
  • Inside the computer, bits – high or low electrical charge, a strong or weak signal, a shiny or dull spot on a CD
  • “Any piece of discrete information can be reduced to a sequence of zeros and ones and thus represented in bits” {?}

NB: Discrete data can only take distinct values; can be numeric or categorical (male or female, green or yellow) –stackexchange 

Example: Show the number 13 in bits

-Have only 2 digits (0 and 1)
-The weight of each digit increases by a factor of 2 from right to left

13 in bits

-The binary number 00001101, or 8+4+1, is the decimal number 13

NB: a binary number is expressed in the binary numeral system or base-2 numeral system which represents numeric values using two different symbols: usually 0 and 1 –Wikipedia 

Values

  • modern computer has > 30 billion bits in its volatile data storage; more in nonvolatile data storage

NB: Volatile memory is computer memory that requires power to maintain the stored info; stored data is lost if the power is off or interrupted —Wikipedia 

  • hard to work with this large quantity of bits
  • Solution: separate bits into chunks (called values) that represent pieces of information
  • Every value has a type that determines its role
  • The 6 basic types of values in JS:
    -numbers
    -strings
    -Booleans
    -objects
    -functions
    -undefined values
  • To create a value — invoke its name
  • Every value has to be stored somewhere
  • Might run out of bits if you use many, many values simultaneously
  • “When you no longer use a value, it will dissipate {?}, leaving behind its bits to be recycled as building material for the next values”

 

Numbers

[make more concise]

  • The value of the number type is a numeric value
  • JS uses 64 bits to store a single number value
  • The amount of different numbers that can be represented is limited
  • With 64 binary digits, 264 different numbers can be represented
  • Computer memory used to be smaller; 8 bits or 16 bits were used to represent numbers
  • Easy to overflow such small numbers – end up with a number that did not fit into the given amount of bits
  • Today, computers have plenty of memory, so overflow occurs only when dealing with astronomical numbers
  • Bits can store negative numbers (one bit indicates the sign of the number)
  • Nonwhole numbers must also be represented (some of the bits store the position of the decimal point)
  • Calculations with integers (whole numbers) are precise
  • Treat fractional digital numbers as ap and proximations, not as precise values (because fractions cannot be expressed by a finite number of decimal digits — and there is only 64 bits available to store them)

 

Arithmetic

  • 100 + 4*11
  • + and * are operators 
  • + represents addition
  • * represents multiplication
  • <<value>> <<operator>> <<value>>
  • An operator between two values applies itself to those values to produce a new value
  • Order of operator application (precedence) is determined by BEDMAS
  • Apply Left to Right if there are multiple operators with the same precedence
  • % : represents the remainder operation — known as modulo or remainder 
  • X % Y : the remainder of dividing X by Y
  • Example: 314 % 100 produces 14, 144 % 12 produces 0 

 

Special Numbers

3 JS values considered numbers but don’t behave like normal numbers:

  1. Infinity : positive infinity
  2. -Infinity : negative infinity
  3. NaN : “Not a Number” – a value of the number type; will get NaN when i.e.  0/0 (zero divided by zero), Infinity – Infinity, any numeric operation that does not yield a precise result

 

Strings

  • string – a basic data type
  • represent text
  • content enclosed in quotes (single, double – but start and end quote must match)
  • i.e. “Hello there!”, ‘On the way to the moon, hold up.’
  •  Characters that are difficult to place within quotes: quotes, newlines (characters you get when you press Enter – basically spaces on a new line)
  • Solution: escaping the character — using: backslash (\)  — when this is inside a quoted text,  it indicates the the character after it has a special meaning
  • i.e. ‘She\’s my sister\’s dog’ means the quotes are a part of the string
  • i.e. ‘ \n ‘ means a newline
  • i.e. ‘ \t ‘ means a tab character
  • i.e. “This is the first line\nAnd this is the second”
    Actual  text:
    This is the first line
    And this is the second
  • When you want a backslash in a string to be just a backslash:
    use \\ (two backslashes)

Example:

console.log(“A newline character is written like \”\\n\”.”)
// -> A newline character is written like “\n”.

  • Strings cannot be divided, multiplied, or subtracted
  • + operator used on strings to concatenate – combines two strings together

Example:

console.log(“con” + “cat” + “e” + “nate”)
// -> concatenate               [not enclosed by single quotes like in Python]

 

Unary Operators

unary operator: operator that takes\operates on one value

binary operator: operator that uses two values

ternary operator: operator that operates on three values

typeof: an unary operator that produces a string value naming the type of the value given to it

Example 1: 
console.log(typeof 4.5)
//-> number

Example 2:
console.log(typeof Infinity)
//-> number

Example 3:
console.log(typeof NaN)
//->number

Example 4:
console.log(typeof 3 > 2)
//-> false

Example 5:
console.log(typeof “x”)
//-> string

NB1: console.log() outputs a message to the Web Console (a way for us to see the result of evaluating something)

NB2: The minus operator (-) can be used as both a binary and an unary operator

Example 6: 
console.log(-(10-2))
//-> -8

 

Boolean Values

Distinguish between two possibilities i.e. yes and no, on and off, …

Boolean type: has two values — true and false

Comparisons

A way to produce Boolean values

Example 1: 
console.log(3 > 2)
//-> true                                     Indicates 3 is greater than 2

Example 2: 
console.log(3 < 2)
//-> false

 

Strings can be compared to each other :

  • strings are ordered alphabetically i.e. “a” < “z”
  • uppercase letters are “less” than lowercase letters i.e. “Z” < “a”
  • non-alphabetic characters (!, -, ?, etc.) are included in the ordering i.e. “.” > “!”,  “?” > “!”
  • comparison is based on the Unicode standard : assigns a number to every character ever needed, including characters from other languages i.e. Japanese, Arabic, Greek, …
  • comparing strings : Left to Right, compare numeric codes of characters one by one
  • other comparison operators:
    >=    greater than or equal to 
    <=    less than or equal to
    ==    equal to
    !=     not equal to
  • one value in JS is not equal to itself : NaN (“not a number”)

Example: 
console.log(NaN == NaN)
//-> false

NB: NaN denotes the result of a nonsensical computation; therefore it isn’t equal to the result of other nonsensical computations.

 

Logical Operators

 Operators on Boolean values

and, or, not
used to “reason” about Booleans 

 

&& represents logical and 
-a binary operator
-its result is true iff both values given to it are true

Example 1:
console.log(true && false)
//-> false

Example 2: 
console.log(true && true)
//-> true

|| represents logical or
-a binary operator
– proudces true if either of the values given to it is true

Example 1:
console.log(false || true)
//-> true

Example 2:
console.log(false || false)
//-> false

! represents not 
-an unary operator
-flips the value given to it

Example 1: 
console.log(!true)
//-> false

Example 2: 
console.log(!false)
//-> true

 

Order of Precedence 

Arithmetic operators (highest)
Comparison operators
&&
|| (lowest)

NB: This order minimizes the use of parentheses.

Example:
console.log(1+1 == 2 && 10*10 > 50)
// 2 == 2 && 100 > 50
// true && true
//-> true

<<value1>> ? <<value2>> : <<value3>>
-represents the conditional/ternary operator
– a ternary operator
-written with a question mark and a colon
– The first value “picks” which of the other two values will come out :
-if true, the second value is chosen
-if false, the third value is chosen

NB: << … >> just represents that a value is written; <<…>> itself is not included in the value

Example 1:
console.log(true ? 1 : 2)
//-> 1

Example 2: 
console.log(false ? 1 : 2)
//-> 2

Undefined Values

Two special values:

null

undefined

represent the absence of a meaningful value (carry no information)

NB1: operations that don’t produce a meaningful value yield undefined because they have to yield some value

NB2:
-there is a difference in meaning between undefined and null (but it doesn’t matter most of the time)
-this is an accident of JS’ design
-treat them as interchangeable (for now)

Automatic Type Conversion

Here we’ll see how JS accepts almost any program given to it, even if they are odd.

type coercion:
– an operator is applied to the “wrong” type of value i.e. “three” + 3
-JS converts that value to the type it wants
-JS uses a set of unpredictable rules to do this

Example 1: 
console.log(8*null)
//-> 0                             null becomes 0

Example 2: 
console.log(“5” – 1)
//-> 4                             string -> number ; “5” becomes 5

Example 3: 
console.log(“5” + 1)
//-> 51                     + tries string concatenation before numeric addition; 1 converted to “1”

Example 4:
console.log(“five” * 2)
//-> NaN

Example 5:
console.log(false == 0)
//-> true

Regarding Ex. 4: When something that doesn’t map to a number i.e. “five”, “undefined”, is converted to a number, the value NaN is produced.

NB: Further arithmetic operations on NaN keep producing NaN.

 

Comparing values of different types using == 

  • most cases: JS converts one of the values to the other value’s type
  • For true to be produced —
    if null is on one side, undefined must be on the other and vice versa

Example 1:
console.log(null == undefined)
//-> true

Example 2: 
console.log(undefined == null)
//-> true

Example 3: 
console.log(null == 0)
//-> false

Example 4:
console.log(undefined == 1)
//-> false

NB: to test whether a value has a real value instead of null or undefined, compare it to null with the == or != operator.

QUESTION: Can you compare it to undefined too?

 

Rules for converting strings and numbers to Boolean values:

  • 0, NaN, the empty string (“”) count as false
  • all other values count as true

Ex. 1: 
console.log(0 == false)
//-> true

Ex. 2: 
console.log(“” == false)
//-> true

For these cases, automatic type conversion is unwanted.

To test whether something refers to the precise value false: 

  • Use two extra operators:
=== 
!==

=== tests whether a value is precisely equal to the other

!== tests whether a value is not precisely equal to the other

Ex: 
console.log(“” === false)
//-> false

In this example, “” counts as false, but it is not precisely equal to the value false.

NB: Use the three-character comparison operators to make certain that both sides are the same type.

QUESTION: Because automatic type conversion could change the type of a value in the comparison?  

 

Short Circuiting of Logical Operators

  • Logical operators && and || handle values of different types strangely
  • They will convert the value on their left side to Boolean type (to decide what to do)
  • Depending on the operator and the result of that conversion, either the original LH-value or RH-value is returned

|| operator
– returns the value to its left when that can be converted to true
-returns RH-value otherwise

Ex. 1:
console.log(null || “user”)
//-> user

Ex. 2
console.log(“Karl” || “user”)
Karl

NB: Therefore || operator can be used as a way to fall back on a default value i.e. give it an expression that might produce an empty value on the left, the value on the right will be used as a replacement

&& operator
– works the other way around
-when LH-value is something that converts to false, it returns that original LH-value
-otherwise, RH-value is returned

Property of && and || operators:
Short-circuit evaluation: expression on right evaluated only when necessary

Ex. 1: true || X
-LH-value is true so the result is true
-X is never evaluated, no what X is

Ex. 2: false && X
-result is false
-X is ignored

Conditional operator
-works similarly
-first expression is always evaluated
-second or third value (the one not picked) is ignored {?}

 

Summary

We made some values and applied operators to them to get new values.

  • Went through four types of JS values: numbers, strings, Booleans, undefined values
  • Values are created by typing in their name (true, false, null, undefined) or value (“abc”, 13)
  • Can combine and transform values with operators
  • Binary operators for
    -arithmetic (+, -, *, /, %)
    -string concatenation (+)
    -comparison (==, !=, ===, !==, <, >, <=, >=)
    -logic (&&, ||)
  • Unary operators:
    -(!) to negate logically
    -(-) to negate a number
    -(typeof) to find a value’s type
  • Ternary operator:
    ( ? : ) – to pick one of two values based on a third value
  • NaN (“not a number”) is the only JS value not equal to itself, because the result of a nonsensical computation cannot equal the result of another nonsensical computation

 

Progress: We can now use JS as a pocket calculator. LOL FML.

 

Eloquent Javascript: Intro – What is Javascript? ;Rough Notes

Resource: Eloquent Javascript, 2nd Edition by Marijn Haverbeke

What is Javascript?

  •  JavaScript (henceforth JS) created in 1995 to add programs to web pages in the Netscape Navigator browser
  • Major graphical web browsers have since adopted JS
  • JS has made modern web applications possible
  • “Modern web applications = applications with which you can interact directly without doing a reload for every action”
  • Also used in websites to provide interactivity

NB: Netscape – a series of web browsers produced by Netscape Communications Corporation (now a subsidiary of AOL); original browser once the dominant browser in terms of usage share (proportion of visitors to web sites that use a certain web browser), but lost to Internet Explorer in the first browser war (competition for dominance in the usage share of web browsers) (first war — Microsoft’s Internet Explorer vs. Netscape’s Navigator)
—Wikipedia: Netscape (web browser)

  • ECMAScript standard : a standard document that describes the way JS should work to ensure that software claiming to support JS really does support JS ; named after Ecma International, the organization that did the standardization
  • ECMAScript and JS can be used interchangeably (two names for the same language)

Disadvantages of JS

  • JS is “ridiculously liberal in what it allows” — almost any command is accepted, but is then interpreted differently
  • Idea behind this design: make programming in JS easier for beginners
  • Reality: Makes finding program errors harder because the system will not point them out to you

Advantages of JS

  • Flexibility allows for many techniques that are impossible in more rigid languages

Different versions

  • Version 3 — widely supported version btwn ~ 2000-2010, the time of JS’s ascent to dominance
  • Version 4 — “changing a living, widely used language … turned out to be politically difficult” — work abandoned in 2008
  • Version 5 — came out in 2009
  • Version 5.1 — 2011 — Editorial changes —w3schools
  • Version 6 — 2015 —  Added classes and modules —w3schools
  • Version 7 — 2016 — added exponential operator (**); added Array.prototype.includes –w3schools
  • This book’s edition came out in 2014 so it will focus on Version 5, which all major browsers support; we should focus on using Version 6, which all major browsers are in the process of supporting

 

  • Platforms on which JS is used: Web browsers, databases i.e. MongoDB, CouchDB (use JS as their scripting and query language)
  • Several platforms for desktop and server programming i.e. notably, Node.js, provides a powerful environment for programming JS outside of the browser

 

Invent with Python — Chapter 3: Writing Programs; Notes

Topics covered:

  • Flow of execution
  • Strings
  • String concatenation
  • Data types (strings, integers)
  • Using the file editor to write programs
  • Saving and running programs in IDLE
  • The print() function
  • The input() function
  • Comments
  • Case-sensitivity

Learn to: store text in variables, combine text, and display text on the screen

Strings

string: a text value

  • string values can be used just like integer and float values
  • can store strings in variables
  • string values start and end with a single quote (‘)
  • or a double quote (“)
  • Ex:
    >>> spam = ‘hello’
    >>> spam
    ‘hello’
    >>> spam = “hello”
    >>> spam
    ‘hello’

NB: Single or double quotes tell Python where the string begins and ends; they are not part of the string value{?}

  • strings can comprise of any keyboard character with no character count limit;
  • Examples:
    -‘Hi there!’
    -‘KITTENS’
    -‘7 apples, 14 oranges, 3 lemons!!’
    -‘0*&#wY%***05FDLKJ okay therkjlajksf568415224599@#$#$!’

 

String Concatentation 

string concatentation: the combination of two strings with the + operator

  • Just like integer and float values do, string values can combine with operators to make expressionsExample:
    >>> ‘Hello’ + ‘World!’             [expression]
    ‘HelloWorld!’                           [expression evaluates to a single string value]
    >>> ‘Hello’ + ‘ World!’            [notice the single space after the first single quote]
    ‘Hello World!’

 

  • + operator works differently on string values vs. integer and float values because they are different data types
  • All values have a data type
    Example:The data type of the value ‘Hello’ is a string.
    The data type of the value 5 is a an integer. 

data type:  tells Python what operators should do when evaluating expressions

  • + operator will concatenate string values but add integer and float values

concatenation errors

NB: Different error types depending on the first value

 

Hello World! 

hello world july 6

How it works

  • Each line of code is an instruction interpreted by the Python interpreter software (will be referred to as Python from now on)
  • These instructions make up the program

Execution: the step Python is at in the program;
ex: when the program starts, the execution is at the first instruction; after executing     the instruction, the execution moves down to the second instruction, and so on etc.

Comments

#This is a comment

This instruction is a comment : any text following a sign (pound sign)

  • Comments are for the programmers — notes of what their code does, usually at the top of the code
  • Comments are ignored by Python

 

Functions 

Function:
-mini-program inside the ‘main’ program
-contains instructions to execute when the function is called

Built-in function: Python-provided function; ex: print(), input()

Function call: an instruction that tells Python to run the code inside the function*
Example:
>>> print(‘Hello World!’)            [function call – a call to the print() function]

*The code inside built-in functions such as print() are not visible to us

A program calls the print() function – Python takes the string between the parentheses as input and displays the text on the screen

QUESTION: what is the visual difference between a function and a function call?

argument: the value between the parentheses in a function call
Example: ‘Hello World!’ is the argument in print(‘Hello World!’)

passing the argument to the print() function – argument(s) inputted between the parentheses {?}

input() function

>>> myName = input()        [an assignment statement]

Variable: myName
Function call: input()

When the function input() is called, the program waits for the user to enter text.
The text string the user enters becomes the value that the function call evaluates to.

NB: Function calls can be used in expressions that values can be used in.

return value: the value that the function call evaluates to/returns

In the case of the input() function, the return value is the string that the user typed in.

Example:
myName input()

The user typed in May.
The input() function call evaluates to the string ‘May’.
The string ‘May’ gets stored in the myName variable.

 

Using Expressions in Function Calls 

>>> print(‘It is good to meeet you, ‘ +myName)      [print() function call]

NB: Arguments are always single values.

  1. Python evaluates this expression
  2. Pass that value as the argument

If Albert is the value stored in the myName variable, the evaluation would progress like this:

print albert

Ending the Program 

A program terminates/exits: stops running
when the program executes the last line

  • Python forgets all of the values stored in the variables, until the program runs again; ex:
    the string stored in myName; when the program runs again and you enter a different name, the program will use that as your name

 

Naming Variables

  • Variable names are case-sensitive; ex: SPAM, spam, Spam, sPAM — are four different variables in Python
  • A bad idea to use different case variables; use descriptive names instead
  • Variable names are usually lowercase
  • Short names are better than long names
  • If there is more than one word in a variable name, capitalise each word after the first word
  • Or add underscores; ex: first_country

Invent with Python — Chapter 2: The Interactive Shell; Notes

Topics Covered — Basic Programming Concepts:

  • Integers and Floating Point Numbers
  • Expressions
  • Values
  • Operators
  • Evaluating Expressions
  • Storing Values in Variables

Integers and Floating Point Numbers

integer (int): a whole number; ex: 5, 600, 76, 1, 0, … etc.

floating point number (float): a fraction or a number with a decimal point; ex: 3.5, 7.998, 23.0, 5.0, … etc.

value: any integer or floating point number

Expressions

python math operators

Expression: comprised of values connected together by operator(s); ex: math problems like 2+2+3/2*2, 1+1, … etc.

NB: There can be any number of spaces between values and operators;
ex:
>>> 2   +                 2
4

Evaluating Expressions

Evaluate an expression: reduce that expression to a single value; ex: getting 15 from 10+5

NB1: A single value is also an expression; ex: the expression 15 evaluates to the value 15

NB2: The / division operator evaluates to a float value; ex: 24/2 evaluates to 12.0

NB3: Math operations w/ float values also evaluate to float values; ex: getting 14.0 from 12.0 + 2

Syntax Errors 

syntax error: Python doesn’t understand the instruction because it is typed incorrectly

Example:
>>> 5 +
Syntax Error: invalid syntax

This error occurred because 5 + is not an expression.
Expressions have values connected by operators. The + operator expects a value after itself, but it is missing.

Storing Values in Variables 

variable:
-like a box that can store a value

statement: an instruction that doesn’t evaluate to any value

assignment statement: instruction to store a value inside a variable; ex: spam = 15
assignment operator: =

spam 15

SUMMARY

There are two types of instruction:

  1. Expression: evaluates to a single value
  2. Statement: doesn’t evaluate to any value

 

Other Notes

  • Python creates a variable the first time this variable is used in an assignment statement
  • A variable stores a value, not an expression; ex: spam = 10 + 5 v.s. spam = 10 + 7 -2 ; they both evaluate to 15; the end result is the same; both assignment statements store the value 15 in the variable spam, not the expressions 10 + 5 or 10 +7-2
  • If a value is stored in a variable, the variable can be used in an expression; ex:
    >>> spam = 1
    >>> spam
    1
    >>> spam + 5
    6
  • Can change the value stored in a variable by entering another assignment statement; ex:
    >>> spam = 15
    >>> spam + 5
    20
    >>> spam = 3
    >>> spam + 5
    8
  • Cannot use a variable before an assignment statement creates it; Python will return NameError b/c no such variable by that name exists yet

Starting with — Invent Your Own Computer Games with Python; Notes

Resource: Invent Your Own Computer Games with Python, 3rd Edition by Al Sweigart

Objective: Learn how to program by making simple video games.

Chapter 1 — Installing Python 

program: instructions in a language that a computer can understand

Python: one such language

Downloading and Installing Python 

Python interpreter software: a program that understands the instructions written in Python

.
.
.

Starting IDLE

IDLE:
Interactive DeveLopment Environment
-A development environment, like a word processing software for writing Python programs
-Starting IDLE is different on each OS
-On Windows, search for IDLE (Python GUI)

interactive shell:
-the window that appears when IDLE is run
-where Python instructions are entered (after the >>> prompt)
-the Python interpreter software will perform them

How to Use this Book

Each chapter begins with a sample run of a program, showing you what the program looks like when you run it.

Type the code for the program into IDLE’s file editor yourself to remember the programming better.

Play around with the code.

Finding Help Online

 

“When asking programming questions, do the following:

  • If you are typing out the programs in this book but getting an error, first check for typos with the online diff tool at http://invpy.com/diff. Copy and paste your code into the diff tool to find any differences from the book’s code in your program.
  • Explain what you are trying to do when you explain the error. This will let your helper know if you are on the wrong path entirely.
  • Copy and paste the entire error message and your code.
  • Search the Web to see whether someone else has already asked (and answered) your question.
  • Explain what you’ve already tried to do to solve your problem. This tells people you’ve already put in some work to try to figure things out on your own.
  • Be polite. Don’t demand help or pressure your helpers to respond quickly.”