You Don't Know JS: Up and Going Summary

You Don't Know JS: Up and Going Summary

CHAPTER 1: INTO PROGRAMMING

A code is a set of programmed instructions that tell the computer the certain kinds it needs to perform. A code is divided into two subgroups; statements and expressions.

• A statement is a group of words, numbers, and operators that performs a specific task and consists of more than one expression, however, most statements end with a semicolon “;”.

    e.g. a = b * 6this is a statement

This is an instruction that tells the computer what to do by getting to the current value stored in the variable

• An expression is any reference to a variable or value, or a set of variable(s) and value(s) combined with operators.

e.g. a = b * 6

This is a complete statement with 4 expressions of which are:

  1. 2 – literal value expression
  2. b – variable expression
  3. b * 6 – arithmetic expression
  4. a = b * 6 – assignment expression

EXECUTING A PROGRAM

In executing a program, the computer needs a special utility that is used to translate code into commands that a computer can understand: this can be either an interpreter or a compiler.

Anything that should be coded should occur inside the console.log(); statement. The log( b ) part is referred to as a function call, this is where we’re handing the b variable to that function, which asks it to take the value of b and print it to the console. In addition, the console. part is an object reference where the log(..) function is located.

Another way of creating output that you can see is to run an alert(..) statement. For example: alert( b ); If you run that, you’ll notice that instead of printing the output to the console, it shows a pop-up “OK” box with the contents of the b variable. However, using console.log(..) is generally going to make learning about coding and running your programs in the con‐ sole easier than using alert(..) because you can output many values at once without interrupting the browser interface. To get input from a user, we use the prompt(…) function

          e.g. age =  prompt ( “Please tell me your age:”);
                console.log (age);

Operators are how actions are performed on variables and values.

Assignment =, as in a = 2.

Math

  + (addition), - (subtraction), * (multiplication), and / (division), as in a * 3. 

Compound assignment

  +=, -=, *=, and /= are compound operators that combine a math operation with 
 assignment, as in a += 2 (same as a = a + 2). 

Increment/decrement

   ++ (increment), -- (decrement), as in a++ (similar to a = a + 1). 

Object property access

    . as in console.log().
   Objects are values that hold other values at specific named locations called 
   properties. obj.a means an object value called obj with a property of the name 
   a. Properties can alternatively be accessed as obj["a"]. 

Equality

 == (loose-equals), === (strict-equals), != (loose not-equals), !== (strict not- 
 equals), as in a == b. 

Comparison

    < (less than), > (greater than), <= (less than or loose-equals), >= (greater than 
     or loose-equals), as in a <= b. 

Logical

        && (and), || (or), as in a || b that selects either a or b. These operators are 
       used to express compound conditionals

Code comments

Commenting in code is not a must but is good practice as the choices you make about how to write your program matter - not only to you, but to other team members and even to your future self

There are lots of opinions on what makes well-commented code; we can’t really define absolute universal rules. But some observations and guidelines are quite useful:

  • Code without comments is suboptimal.
  • Too many comments (one per line, for example) is probably a sign of poorly written code.
  • Comments should explain why, not what. They can optionally explain how if what’s written is particularly confusing.

Types of comment:

  • // This is a single-line comment
  • /* But this is a multi line comment.

Variable: is a symbolic container because value in this container can vary over time as needed. The variable is usually declared in some programming languages so as to hold a specific type of value. A variable is declared using the var statement.

e.g.                  var amount = 20;                                             
                               amount = amount * 2 ;                                                                                                          
                               console.log (amount);

So the amount variable here is the symbolic container holding the number 20. Blocks: this is wrapping one or more statements inside a curly-brace pair { … }

e.g. var amount = 20;
              {
                      amount = amount * 2 ; 
                      console.log (amount);                                                                                                                           
                }

Conditionals: decision statements

if(Condition){statement(s);}  means If this condition is true, do the following.
```
if(10<20){console.log(“10 is smaller than 20”);}
else{console.log(“10 is greater than 20”)}
   If this 10<20, do the this, else do that.
```

Loops: repeating a set of actions until a certain condition fails and there are 3 types of loops of which are:

  1. for()
  2. while()
  3. do{}while() for(): for (var i = 0; i <= 9; i = i + 1) { console.log( i ); } // 0 1 2 3 4 5 6 7 8 9 while(): var i = 0;

// a while..true loop would run forever, right? while (true) { // stop the loop? if ((i <= 9) === false) { break; }

console.log( i );
i = i + 1;

} // 0 1 2 3 4 5 6 7 8 9 do{}while(): do { console.log( "How may I help you?" );

// help the customer...

numOfCustomers = numOfCustomers - 1;

} while (numOfCustomers > 0);

Functions: is named section of code that can be “called” by name, and the code inside it will be run each time. Functions can optionally take arguments also known parameters

Scope: technically called lexical scope rules say that code in one scope can access variables of either that scope or any scope outside of it.

function one() {
 // this `a` only belongs to the `one()` function
 var a = 1;
 console.log( a );
}
function two() {
 // this `a` only belongs to the `two()` function
 var a = 2;
 console.log( a );
}
one(); // 1
two(); // 2

a scope can be nested inside another scope

e.g.  
function outer() {
 var a = 1;
 function inner() {
 var b = 2;
 // we can access both `a` and `b` here
 console.log( a + b ); // 3
 }
 inner();
 // we can only access `a` here
 console.log( a ); // 1
}
outer();

CHAPTER 2: INTO JAVASCRIPT

There are 6 data types in JS of which are:

  1. String
  2. Number
  3. Boolean
  4. Null and Undefined
  5. Object
  6. Symbol (new to ES6)

So JavaScript provides a typeof operator and what this does is that it can examine a value and tell exactly what data type it is:

 var a;
typeof a;                        // "undefined"

a = "hello world";
typeof a;                           // "string"

a = 42;
typeof a;                           // "number"

a = true;
typeof a;                           // "boolean"

a = null;
typeof a;                           // "object"--weird, bug

a = undefined;
typeof a;                          // "undefined"

a = { b: "c" };
typeof a;                           // "object"

The object type refers to a compound value where you can set properties (named locations) that each hold their own values of any type. This is perhaps one of the most useful value types in all of JavaScript.

var obj = {
     a: "hello world",
 b: 42,
 c: true
};
obj.a;         // "hello world"
obj.b;         // 42
obj.c;         // true

• An array is an object that holds values (of any type) not particularly in named properties/keys, but rather in numerically indexed positions. are special objects (as typeof implies), they can also have properties, including the automatically updated length property.

var arr = [
 "hello world",
     42,
     true
];
arr[0];     // "hello world"
arr[1];     // 42
arr[2];     // true
arr.length;     // 3

typeof arr;     // "object"

Equality

  1. “==” — loose equality
  2. “===” — strict equality
    var a = "42",b = 42;
    a==b;//true
    a===b;//false
    
    • We must avoid “==” while comparing with : 0,"",[],true/false,null

• With comparison of array, as noted in this chapter is that array comparison will always give false ALWAYS

• Behavior of != and !== is loose and strict respectively.

• Inequalities are the same as the basic ones thought in maths (<=, >=, <, >).

Closures: can be thought of a way to “remember” and continue to access a function’s scope (its variables) even once the function has finished running. function makeAdder(x) {

 // parameter `x` is an inner variable
     // inner function `add()` uses `x`, so
     // it has a "closure" over it
 function add(y) {
 return y + x;
 };
     return add;
}

The reference to the inner add(..) function that gets returned with each call to the outer makeAdder(..) is able to remember whatever x value was passed in to makeAdder(..)

•IIFEs: Immediately Invoked Function Expressions. As the name suggests these gets invoked immediately after function declaration:

(function IIFE(){
 console.log( "Hello!" );
})();
// "Hello!"

•Modules: let you define private implementation details (variables, functions) that are hidden from the outside world, as well as a public-API that is accessible from the outside and it is the most common usage of closure in JavaScript known as the module pattern.

function User(){
     var username, password;

 function doLogin(user,pw) {
 username = user;
 password = pw;
         // do the rest of the login work
 }

 var publicAPI = {
 login: doLogin
 };
     return publicAPI;
}
// create a `User` module instance
var fred = User();

fred.login( "fred", "12Battery34!" );

• use Strict: It’s a good programming practice to use this as it refrains you to do logical errors by not allowing you to make global variables.

• Transpiling: Process of reading source code written in one programming language, and producing the equivalent code in another language.

e.g.
function foo(a = 2) {    Here ES6 adds a feature called 
     console.log( a );    “default parameter values”
}

foo();         // 2
foo( 42 );     // 42


function foo() {    
     var a = arguments[0] !== (void 0) ? arguments[0] : 2;    
 console.log( a );    
} 
it checks to see if the arguments[0] value is undefined

• Prototypes: When you reference a property on an object, if that property doesn’t exist, JavaScript will automatically use that object’s internal prototype reference to find another object to look for the property on. You could think of this almost as a fallback if the property is missing. The internal prototype reference linkage from one object to its fall‐ back happens at the time the object is created. The simplest way to illustrate it is with a built-in utility called Object.create(..).

e.g.
var foo = {
     a: 42
};

// create `bar` and link it to `foo`
var bar = Object.create( foo );

bar.b = "hello world";

bar.b;         // "hello world"
bar.a;         // 42 <-- delegated to `foo

• this identifier: If a function has this reference inside it, that this reference usually points to an object. But which object it points to depends on how the function was called. It’s important to realize that this does not refer to the function itself, as is the most common misconception

  e.g.
function foo() {
     console.log( this.bar );
}
var bar = "global";

var obj1 = {
 bar: "obj1",
     foo: foo
};

var obj2 = {
 bar: "obj2"
};
// --------

foo();             // "global"

obj1.foo();         // "obj1"
foo.call( obj2 );     // "obj2"
new foo();         // undefined

There are four rules for how this gets set, and they’re shown in those last four lines of that snippet:

  1. foo() ends up setting this to the global object in non-strict mode—in strict mode, this would be undefined, and you’d get an error in accessing the bar property—so "global" is the value found for this.bar.
  2. obj1.foo() sets this to the obj1 object.
  3. foo.call(obj2) sets this to the obj2 object.
  4. new foo() sets this to a brand-new empty object

Chapter 3 of You don't know JS: Up and Going emphasizes more on the remaining series of You Don't Know JS