the-modern-javascript-bootcamp/notes/chapter3_javascript-basics_varaibles-and-flow-control.md

1.8 KiB

Chapter 3: JavaScript Basics: Varaibles and Flow Control

Booleans and Comparison Operators

Booleans in JS:

let isFreezing = true;
let isBoiling = false;

Use comparison to evaluate to Booleans:

  • Equality Operator: ===
  • Not-equality Operator: !==
  • Less than Operator: <
  • Greater than Operator: >
  • Less than or equal to Operator: <=
  • Greater than or equal to Operator: >=

If Statements and ifelse statements

if (condition) {
    // executed if true
} else if {
    // executed else if false
} else {
    // executed after all justified
}

Logical "And" and "Or" Operators

  • Logical "And" Operator: &&
  • Logical "Or" Operator: ||

Variable Scope

JS use Lexical Scope (Static Scope) has 2 types of scope:

  • Global Scope = Defined outside of all code blocks
  • Local Scope = Defined inside a local scope (e.g. function block or if stat)

In a scope you can access variables defined in that scope, or in any parent/ancestor scope.

Variable Shadowing: In local scope, we can difine same variable name to overwrite/shadow parent scopel

let name = 'Andrew';
if (true) {
    let name = 'Mike';

    if (true) {
        console.log(name); // => Mike
    }
}

if (true) {
    console.log(name); // => Andrew
}

Assigning variable also need take scope into consideration

Leaked Global variable: If a variable in local scope is not defined, it will look up that variable name in parent scope, ancestor scope, until global scope. If not found in global scope as well, JS will define it in global scope

if (true) {
    if (true) {
        let name = 'Jan' // => JS will create a global name
        console.log(name)
    }

    if (true) {
        console.log(name) // => 'Jan' as it's leaked global variable
    }
}