Skip to content

Instantly share code, notes, and snippets.

@Doaxan
Created January 7, 2022 02:49
Show Gist options
  • Select an option

  • Save Doaxan/024e3278316990becae1451a448326bb to your computer and use it in GitHub Desktop.

Select an option

Save Doaxan/024e3278316990becae1451a448326bb to your computer and use it in GitHub Desktop.
JavaScript Cheatsheets

JavaScript

JS Basics

The <script> Tag

  • In HTML, JavaScript code is inserted between <script> and </script> tags.

  • Scripts can be in the <body>, or in the <head> section of an HTML page, or both.

  • Example :

<script>
document.getElementById("demo").innerHTML = "My First JavaScript";
</script>

External JavaScript

  • JavaScript files have the file extension .js.
  • Put name of script file in the src attribute of a <script> tag.

Example :

// adding a single file
<script src="myScript.js"></script>
  
// adding several files
<script src="myScript1.js"></script>
<script src="myScript2.js"></script>

Declaring Variables & Console

// VARIABLE DECLARATION
// In js we use lower camelCase
let firstName = "Michael";
  
// CONSTANT DECLARATION 
// uppercase by convention but can be changed
let PI = 3.1415;
  
// OUTPUT TO CONSOLE
console.log(firstname); 
  
// Console will show us errors even if we don't use 'console.log()'

Objects & Primitives

// Values are either Objects or Primitives
// OBJECTS
let me = {
  name = "Michael"
};

// PRIMITIVES
let firstName = "Michael";
let age = 40;

// THE 7 PRIMITIVE DATA TYPES
// 1. Number data type (ints, floats are all Numbers)
// Numbers default to floats
let age = 50;
let num1 = 5.5;

// 2. string
let firstName = "Michael";

// 3. boolean
let adult = true;
let teen = false;
  
// 4. undefined (unassigned)
let children;
console.log(childre); // undefined
console.log(typeof children); // undefined
  
// 5. null (empty value, similar to Undefined, details later)

// 6. symbol(ES2015): value that is unique & cannot be changed (not useful for now)
  
// 7. BigInt(ES2020): larger integers
  • Js is a dynamic typing language, so we do not need to define the data types ourselves.
// SHOW TYPE - typeof()
typeof(true); // boolean
typeof false; // boolean

Let, Const Var

// LET - reassignment is possible -
let age = 30;
age = 31;

// CONST - can not reassign - it's immutable -
// we can not declare empty const
const birthYear = 1991;
// birthYear = 2000; -> TypeError

// VAR - should be avoided, old way -
// var will be explained later but never use it
var job = "programmer";
job = "teacher";

// NO DECLARATION
// creates a global object, no scope, bad idea.
lastName = "Seutin";
console.log(lastName); 

Operators

// ARITHMETIC OPERATORS
const a = 10;
const b = 3;

let x = a + b; // 13
x = a - b; // 7
x = a * b; // 30
x = a ** b; // 1000
x = a / b; // 3.3333333
x = a % b; // 1
  
// STRING CONCATENATION
const fName = "Boris";
const lName = "Seutin";
console.log(fName + " " + lName);

// ASSIGNMENT OPERATORS
let x = 15; // 15
x += 10; // 25
x -= 10; // 15
x *= 2; // 30
x /= 2; // 15
x++; // 16
x--; // 15

// COMPARISON OPERATORS (to produce boolean values)
const num1 = 100;
const num2 = 200;
console.log(num1 < num2); // true
console.log(num1 > num2); // false
console.log(num1 <= num2); // true
console.log(num1 >= num2); // false
  
// OPERATOR PRECEDENCE
// refer to MDN js operator precedence table

Strings & Template Literals

// TEMPLATE LITERALS
const fName = "Michael";
const lName = "Kennedy";
const age = 33;
let intro = `My name is ${fName} ${lName} and I am ${age} years old.`;
console.log(intro);

// we can write any JS inside the ${} of Template Literals
const birthYear = 1999;
const currentYear = 2025;
let myAge = `I am ${fName} and I am ${currentYear - birthYear} old.`;
console.log(myAge);

// we can also use Template Literals for any reg strings
console.log(`Que Paso Amigo!`);

// use Template Literals for multi-line strings
// just hit return
console.log(`this is 
multiple line
string.`);

Type Conversion & Coercion

Conversion: we do it explicitly. Coercion: js does it implicitly.

// CONVERSION 
// (String to Number)
let birthYear = "1972";
birthYear = Number(birthYear);
console.log(birthYear + 18); // prints 1990

// (Number to String)
console.log(String(20)); // prints String "20"

// COERCION 
// (Number to String w +)
console.log("I am " + 23 + " years old"); // String "I am 23 years old"

// (string to Number with minus sign)
console.log("23" - 10); // Number 13

// be careful with + sign it does not convert to Number
console.log("23" + 5); // String "235"

// the * sign (multiplier) converts Strings to Numbers
console.log("10" * "5"); // Number 50

// the / sign (dividing) converts Strings to Numbers
console.log("10" / "5"); // Number 2

// the logical operators convert Strings to Numbers
// problem when I tried console.log("10" > "5"): -> false ??
console.log('23' > '18'); // Boolean True

Truthy & Falsy values

. values that become false or true when converted to booleans.

// 5 Falsy Values: 0, '', undefined, Null, NaN
// FALSY
console.log(Boolean(0)); // false
console.log(Boolean('')); // false
console.log(Boolean(undefined)); // false
console.log(Boolean(NaN)); // false

// TRUTHY
console.log(Boolean(33)); // true
console.log(Boolean("hello")); // true
console.log(Boolean({})); // empty object - true

// examples
let money = 0;
if(money){
    console.log("don't spent it all")
}else{
    console.log("you should get a job")
}

let height;
if(height){
    console.log("YAY, height is defined")
}else{
    console.log("height is UNDEFINED, or height = 0")
}

Equality Operators: == vs ===

// strict equality '==='
// '===' does not perform type coercion
let age = 18;
if(age === 18){
    console.log("you just became an adult")
}

// loose equality '=='
// '==' does type coercion
console.log(age === 18); // true
console.log(age == 18); // true
console.log('18' === 18); // false (not type coersion)
console.log('18' == 18); // true (does type coercion)

// avoid the 'loose' equality '=='
// '==' has many weird rules & results

CONDITIONAL LOGIC

If Else

const age = 19;

if (age >= 18){
    console.log(`old enough`)
} else {
    console.log(`too young`)
}

Boolean Logic

// &&
let age = 18;
console.log(age > 15 && age === 18); // true

// ||
let num = 10;
console.log(num > 20 || num < 15); // true

// !
let name = "Michael";
console.log(!name); // false

Switch Statement

const day = 'saturday';

switch(day){
  case 'monday':
    console.log("Do code games!");
    break;
  case 'tuesday':
    console.log("Do code games!");
    break;
  case 'wednesday':
    console.log("C++");
    break;
  case 'thursday':
    console.log("Python");
    break;
  case 'friday':
    console.log("Javascript");
    break;
  case 'saturday':
    console.log("Math");
    break;
  case 'sunday':
    console.log("sunday");
    break;
  default:
    console.log("not a week day");
}

Statements & Expressions (Hight Level View)

// EXPRESSIONS produce a value
console.log(1999); // 1999 is an expression
console.log(3*2); // 3*2 is an expression
console.log(true && false && true); // false is a boolean value

// STATEMENTS are complete sentences
// STATEMENTS do not produce a value
// if statement below is a statement
if(24 > 22){
  const str = ("24 is larger");
}

Ternary Operator

const age = 23;
age >= 18 ? console.log("adult") : console.log("not adult");

// storing Ternary in a variable
const drink = age >= 18 ? "cocktail 🍹" : "agua 💧";

// Ternary inside Template Literal
console.log(`At my age I drink ${age >= 18 ? "beer" : "juice"}.`)

for loop

for (let i = 0; i < 10; i++){
    console.log(i + 1);
}

// CONTINUE
const arr = [123, "apple", 234, "banana", 334, "cantaloupe"];
for (let i = 0; i < arr.length; i++){
    if (typeof arr[i] === "string") {
        console.log(arr[i]);
    }
    else {
        continue;
    }
}

// BREAK
const nums = [1, 2, 3, 4, 5, 6, 7, 8, 9, 10];
for (let i = 0; i < nums.length; i++){
    if (nums[i] === 9) break;
    console.log(nums[i]);
}

while loop

let n = 0
while(true){
  console.log(n);
  n += 1;
  if(n == 11)break;
}

JS Functions

*'use strict';: place this code at the beginning of any js file to have js warn us of errors.

Generic Functions (Function Declaration)

// can be called before being defined.
function calcAge1(birthYear) {
    return 2022 - birthYear;
}

Anonymous Function (Function Expression)

// can not be called before being definde.
const calcAge2 = function (birthYear) {
    return 2022 - birthYear;
}
console.log(calcAge2(2000));

Arrow Function (shorter to write)

They do not get a this keyword (more on that later).

// ONE LINER
// return is implicit for one liner functions.
const calcAge3 = birthYear => 2022 - birthYear;

// LONGER ARROW FUNCTION
// curly brackets and write return explicitly in longer functions.
const ageUntilRetirement = birthYear => {
    const age = 2022 - birthYear;
    const retirement = 65 - age;
    return retirement;
}

// MULTI-PARAMETER ARROW FUNCTION
// paranthesis for more than one parameter.
const ageUntilRetirement2 = (birthYear, name) => {
  const age = 2022 - birthYear;
  const retirement = 65 - age;
    return `${name} will be able to retire in ${retirement} years`;
};

Functions Calling Other Functions

function cutFruitPieces(fruit){
  return fruit * 4;
}

function fruitProcessor(apples, oranges){
  const applePieces = cutFruitPieces(apples);
  const orangePieces = cutFruitPieces(oranges);
  
  const juice = `juice with ${applePieces} pieces of apples and ${orangePieces} pieces of oranges.`;
  return juice
}

Data Structures - Basics -

Arrays (Intro)

// Arrays are mutable (they are not primitive values)
// Array Declaration 1
const friends = ["Michael", "Peter", "Thomas"];
console.log(friends);
console.log(friends[0]);
console.log(friends.length);
friends[1] = "Dufus";
console.log(friends[1]);

// Array Declaration 2
const years = new Array(1991, 2020, 1972);
console.log(years);
console.log(years[2]);
console.log(years.length);

// Arrays can store different types of Expressions
const michael = ["Michael", "Seutin", 2000 - 28];
console.log(michael);

Arrays (Methods)

const fruits = ["Apple", "Banana", "Cantaloupe"];
// push() - adds element to the end of array
fruits.push("Dragonfruit");

// unshift() - adds element ot the beginning of array
fruits.unshift("Apricot");
console.log(fruits);

// push() & unshift() also returns the lenght of the array
console.log(fruits.push("Date")); // returns 6

// pop() - removes last element of array
fruits.pop(); // removes and returns last element

// shift() - removes first lement of array
const firstEle = fruits.shift(); // removes and return first element
console.log(firstEle); // prints Apricot

// indexOf() - returns 1st index at which ele is found or -1 if not found
console.log(fruits.indexOf("Banana")); // returns 1

// includes() - returns true or false whether an ele is present or not
console.log(fruits.includes("Cantaloupe")); // returns true
console.log(fruits.includes("Rock")); // returns false

Objects

// Objects have name(key) & value pairs
// Keys === Properties
// Object Literal Syntax (1st way of declaring objects)
var myCar = {
  make: "Ford",
  model: "Mustang",
  year: 1969,
};

// second way to declare objects
var myCar = new Object();
myCar.make = "Ford";
myCar.model = "Mustang";
myCar.year = 1969;

// objects can contain any values or values as expressions
const michael = {
    fname: "Michael",
    lname: "Sutton",
    age: 2022 - 1999,
    friends: ["Albert", "Bob", "Charlie"]
};
// Object Dot & Bracket Notation
const michael = {
  fname: "Michael",
  lname: "Sutton",
  age: 2022 - 1999,
  friends: ["Albert", "Bob", "Charlie"],
};

// Access the property value with dot
console.log(michael.fname); // returns Michael

// Access the property value with []
// use a STRING ["fname"] to access property value.
console.log(michael["fname"]); // returns Michael

// with [] notation we can include expressions
const nameKey = "name";
console.log(michael['f' + nameKey]);
console.log(michael['l' + nameKey]);

// real world example of using []
const info = prompt("what do you want to know about Michael? fname, lname, age?");
console.log(michael[info]); // returns info or undefined if user input is bad

// using dot or [] notation to change property values
michael.fname = "Miguel";
michael["lname"] = "Satan";

Object Methods

// Adding Function to OBJECT values
const michael = {
    fname: "Michael",
    lname: "Sutton",
    birthYear: 1991,
    job: "student",
    friends: ["Michael", "Peter", "Steven"],
    hasDriversLicense: true,
    // Below function is called a Method (cos inside object)
    calcAge: function (birthYear) {
        return 2222 - birthYear;
    }
};

// Calling the object method
console.log(michael.calcAge(1881));
console.log(michael["calcAge"](1883));

// THIS keyword
const michael = {
    fname: "Michael",
    lname: "Sutton",
    birthYear: 1991,
    job: "student",
    friends: ["Michael", "Peter", "Steven"],
    hasDriversLicense: true,
    // This = object michael
    calcAge: function () {
        // prints michael object
        console.log(this);
        return 2222 - this.birthYear;
    }
};

// Calling the object method
console.log(michael.calcAge());

DOM - Basics

The DOM : Document Object Model

  • When a web page is loaded, the browser creates a DOM of the page.
  • The HTML DOM model is constructed as a tree of Objects.
  • The first Object at the top of the tress is called document
  • DOM & DOM methods are part of Web API's.
  • Web API are like libraries that browsers implement and that we can access from our JS code.
  • DOM allows us to access a node’s attributes, such as its class, id, and inline style.

Accessing the DOM

  • document is the Entry point, that's why we start the command document.querySelector() with the word document.
  • document.body to access the body.
  • document.head to access the head.
  • .innerHTML gets or sets the HTML or XML markup contained within the element.
  • .innerHTML property can also add any valid HTML, including properly formatted elements.

Examples

  • document.body.innerHTML = "Hello World" will print "Hello World" to the page.
  • document.body.innerHTML = "<h2>heading</h2>"; assigns an h2 element as a child inside the <body> ele.

JS & the DOM < CSS Selectors >


.querySelector();

  • .querySelector(); returns 1st Element that matches selector, or group of selectors. If no matches, null is returned.
  • document.querySelector("p"); get the first <p> element in the document.
  • document.querySelector(".example"); get the first element in the document with class="example".
  • document.querySelector("#demo").innerHTML = "Hello World!"; change the text of an element with id="demo".
  • document.querySelector("p.example"); get the 1st <p> ele in the doc with class="example".
  • document.querySelector("div > p"); get the 1st <p> ele in the doc where parent is a <div> ele.
  • document.querySelector("a[target]"); get the first <a> element in the document that has a "target" attribute.

.getElementByID();

  • document.getElementById('bio').innerHTML = 'The description'; this is another option to select by ID.

.querySelectorAll();

  • var x = document.querySelectorAll(".example"); get all elements in the document with class="example".
  • Add an even listener to SelectAll:
for (let i = 0; i < x.length; i++){
  x[i].addEventListener("click", function(){ ... do smth ...});
}

Element.classList & className REDO

  • .classList("myClass") remember that we are passing a class not selecting it so not . needed here.
  • Although the classList property itself is read-only, you can modify its associated DOMTokenList using the add(), remove(), replace(), and toggle() methods.
  • Examples:
const div = document.createElement('div');
div.className = 'foo';

// our starting state: <div class="foo"></div>
console.log(div.outerHTML);

// use the classList API to remove and add classes
div.classList.remove("foo");
div.classList.add("anotherclass");

// <div class="anotherclass"></div>
console.log(div.outerHTML);

// if visible is set remove it, otherwise add it
div.classList.toggle("visible");

// add/remove visible, depending on test conditional, i less than 10
div.classList.toggle("visible", i < 10 );

console.log(div.classList.contains("foo"));

// add or remove multiple classes
div.classList.add("foo", "bar", "baz");
div.classList.remove("foo", "bar", "baz");

// add or remove multiple classes using spread syntax
const cls = ["foo", "bar"];
div.classList.add(...cls);
div.classList.remove(...cls);

// replace class "foo" with class "bar"
div.classList.replace("foo", "bar");

Adding Elements with document.createElement()

  • document.createElement() method creates and returns a reference to a new Element Node with the specified tag name.
  • document.createElement() does not actually add the new element to the DOM, it must be attached with a method such as element.appendChild().
  • Example:
let btn = document.createElement("BUTTON");   // Create a <button> element
btn.innerHTML = "CLICK ME";                   // Insert text
document.body.appendChild(btn);               // Append <button> to <body>

DOM className Property

  • className property is used to set or return the value of an element’s class attribute. Using this property, the user can change the class of an element to the desired class.
  • HTMLElementObject.className; returns the className property.
  • HTMLElementObject.className = "class"; sets the className property.

Useful DOM Manipulations

  • document.getElementById('sign').hidden = true; The code above did not remove the element from the DOM, but rather hid it. This is not the same as setting the CSS visibility property to hidden.
  • Because the .querySelector() method returns the first paragraph, the following code would remove the first paragraph in the document:
let paragraph = document.querySelector('p');
document.body.removeChild(paragraph);

Change Content & Access CSS Style

  • document.querySelector("#demo").innerHTML = "Hello World!"; change the text of an element with id="demo".
  • document.querySelector(".myclass").textContent = "my-new-content"; not sure how it's diff than .innerHTML.
  • .style property of a DOM element provides access to the inline style of that HTML tag.
  • element.style.property format, with the property representing a CSS property.
  • style.width = "15rem" when specifying a style ALWAYS specify a string.
  • following code selects the 1st ele with a class of blue and assigns blue as the background-color:
let blueElement = document.querySelector('.blue');
blueElement.style.backgroundColor = 'blue';
  • backgroundColor unlike CSS, the DOM style property does not implement a hyphen such as background-color, but rather camel case notation.

Event Listeners

Select your element, add your event listener.
Two parameters: 1. pass your event name. 2. pass a function (event handler):

document.querySelector(".check").addEventListener('click', function(){
console.log(document.querySelector('.guess').value);});

.onclick property

  • .onclick property allows you to assign a function to run on a click event on an element:
let element = document.getElementById('interact');
element.onclick = function() { element.style.backgroundColor = 'blue' };

Key Events - Global Listeners

  • document.addEventListener('keydown', ...); fired when any key is pressed < most common >;
  • document.addEventListener('keyup', ...); fired when key is released.
  • document.addEventListener('keypress', ...); fired when key is held.
  • document.addEventListener('keydown', function(e){..}); Js will pass the event into our e param. Example:
document.addEventListener('keydown', function (e) {
  if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
    closeModal();
  }
});

JS Theory Overview(Important)

JS is High Level

  • JS does not have to manage hardware, memory such as:

CPU / Ram

  • Low level languages such as C or C++ need to manage memory.
  • JS use abstractions to manage hardware / memory.
  • The downside is that JS will never be as fast as low level languages.

JS uses Garbage Collection

  • garbage collection makes it possible for JS developer to have to worry about memory.
  • GC stands for Garbage Collection:
    • is a form of automatic memory management.
    • GC attempts to reclaim memory which was allocated by the program, but is no longer referenced—also called garbage.

JS is an Interpreted or - Just-in-time Language

  • machine code is the zeros and ones that the cpu understand.
  • interpreter / compiler both turn our high level code to machine code.
  • JS uses and interpreter.

JS Engine

  • JS Engine is simply a computer program that executes JS code.
  • Most browser have their own JS engine.
  • Google V8 engine is the most common JS engine.
    • the V8 engine powers google chrome & NodeJS.
    • other browsers have their own JS engines.
  • Every JS engine has:
    • 1.call stack
    • 2.heap

Call Stack

  • Call Stack is where our code is executed.
  • Call Stack uses execution context.

Heap

  • Heap is an unstructured memory pool.
  • Heap contains all the objects our program need.

Compilation vs Interpretation

Compilation - 2 Step Process -
  • Compilation the entire code is converted into machine code at once.
    • It's then written to a binary file that can be executed by any computer.
    • SOURCE CODE -> compilation -> MACHINE CODE (Portable File) -> execution -> PROGRAM RUNNING.
    • Execution can happen way after the compilation.
    • Every program on my computer has been compiled before.
    • It's only executed when I run my programs.
Interpretation - 1 Step -
  • Interpreter runs through the source code & execute it line by line.
    • Read & Execute at the same time.
    • Code still needs to be conversted to machine code but it happens right before being executed, not ahead of time.
  • Interpreter are slower than Compilers.
  • JS was purely an interpreted language before.
Modern JavaScript - Just-in-time Compilation -
  • Modern JS uses a mix between compilation & interpretation.
    • this is called just-in-time compilation.
Just-in-time (JIT) Compilation
  • JIT Steps:
    • SOURCE CODE -> compilation -> MACHINE CODE (NO Portable File) -> execution -> PROGRAM RUNNING.
    • Almost like a reg compiler except that there is no portable file, so code is executed immediately.
Steps of the JS Engine
  • Step 1: parsing the code means the engine reads the code.
    • AST is the Abstract Syntax Tree is the Data Structure where the parsing is places.
  • Step 2: compilation converst code to machine code.
  • Step 3: execution code gets executed right away.
    • that is the Just-In-Time Compilation part.
    • execution happen in the call stack. In the background the code is still being optimized & recompiled.
      This constant optimization & update is what makes modern JS Engine such as the V8 so fast.
JS Runtime
  • runtime we can imagine it as a big container that includes all the things we need to use JS, in this case in the browser.
  • runtime includes the JS Engine, plus the Web APIs and Callback Queue.
    • Web API are functionalities provided to the engine, but not part of the JS language.
    • Callback queue contains all the callback functions that are ready to be executed.

JS is a Multi-Paradigm Language

  • paradigm An approach & mindset of structuring code, which will direct your code style & technique.
  • 3 popular paradigms are:
      1. Procedural Programming.
      1. Object Oriented Programming (OOP).
      1. Functional Programming (FP).
  • paradimns can also be clasiffied as imperative or declarative.

while many languages are only procedural or OOP, or functional, JS does all of it.

JS is a Prototype-based object oriented

  • This means that almost everything in JS is an object.
  • primitive values such as numbers, strings.. are the exception to being objects.

JS is a First-Class Functions language

  • In a language with first-class functions, functions are simply treated as variables.
  • We can pass them into other functions, & return them from functions.

JS is a Dynamically typed language

  • we don't need to assign data types to variables:
let x = 23;
let y = 19;
x = "Michael";
  • as seen above, data type of variable is automatically changed.

JS is Single-Threaded

  • concurrency model is how the JS engine handles multiple tasks happening at the same time.
  • JavaScript runs in one single thread, so it can only do one thing at a time.
  • thread is a set of instructions that is executed in the CPU.
  • So what do we do if there is a long-running task ? (next section).

JS uses Non-Blocking Event Loop

  • By using an event loop we take long-running tasks, executes them in the "background", and puts them back in the main thread once they are finished.

Execution Context

  • Execution Context Environment in which a piece of JS is executed. Stores all necessary info for some code to be executed.
  • Execution Context JS code always run inside an Execution Context.
  • Execution Context contains Your Code and:
    • this <keyword> except for arrow functions.
    • Scope Chain.
    • Variable Environment.
      • let, const, and var declarations.
      • functions.
      • argument objects except for arrow functions.

Execution Context Analogy

  • Imagine you order a pizza to be delivered.
  • The pizza represents the code you write.
  • The pizza will come in a BOX that has the Pizza, Cutlery, Napkins, and Receipt.
  • The BOX = EXECUTION CONTEXT.

Global Execution Context

  • Global Execution Context there is always only one for each program.

Other Execution Contexts

  • Other Execution Contexts are created for functions.

Call Stack

  • Call Stack is composed of all the execution contexts.
  • Call Stack is where the execution contexts get stacked on top of one another to keep track of where we are in the execution process.

Scoping

  • scoping how our program's variables are organized & accessed.
  • lexical scoping scoping is controlled by placement of functions & blocks in the code.
  • scope of a variable region of our code where a certain variable can be accessed.
  • scope is the space or environment in which a certain variable is declared.
    • global scope
    • function scope
    • block scope

var, let, const Scopes

  • var function scope but not block scopes, so we can access then outside blocks.
  • let if declared inside a block, only accessible inside the block.
  • const if declared inside a block, only accessible inside the block.

Hoisting

  • hoisting makes some types of variables accessible in the code before they are declared.
    • Variables lifted to the top of their scope.
    • Before execution, code is scanned for variable declarations, and for each new variable, a new property is created in the variable envionment object.

this keyword

  • this special variable that is created for every execution context (every function).
  • this takes the value (points to) the "owner" of the function in which the this keyword is used.
  • this is not static. It depends on how the function is called.
  • Method this = { Object that is calling the method }.
  • Simple Function Call this = { undefined } in strict mode, otherwise: window (in the browser).
  • Arrow Functions this = { this of surrounding function (lexical this ) }.
  • Event Listener this = { DOM element that the handler is attached to }.

this keyword is NOT

  • this does NOT point to the function itself, and also NOT to the variable envionment of the function.

Primitives versus Objects in Memory

JS Engine ( Review )

  • JS Engine is composed of:
    • Call Stack
    • Heap

Primitives

  • Primitives are stored in the call stack.

Primitives - aka (Primitive Types)

  • Number
  • String
  • Boolean
  • Undefined
  • Null
  • Symbol
  • BigInt

Primitive Value Example

'use strict';

let age = 30;
let oldAge = age;
age = 31;
console.log(age);
console.log(oldAge);

What Happens in the Stack

  • age variable:
    • Identifier: age.
      • The identifier age points to the address 001 and not to the value 30.
    • Address: 0001.
    • Value: 30.
  • oldAge is set to equal age so at first it will also point to the address 001.
  • but once we set age to a different value (31), then age will point to a new different address, maybe 002.

Objects

  • Objects are all stored in the memory heap.
    • stored in the execution context in which they are declared.

Objects - aka (Reference Types)

  • Object literal
  • Arrays
  • Functions
  • Many more ...

Object Value Example

'use strict';

const me = {
    name: "Mike",
    age: 30
};

const friend = me;
friend.age = 40;

console.log("Friend: ", friend); // age = 40
console.log("Me: ", me); // age = 40

What Happens in the Heap

  • me object:
    • me object will also have an address (D30F) and a value ({name: "Mike", age: 30}).
    • but me will point to an address in the Stack (004) which holds the address of the value in the heap(D30F).
    • so the memory in the call stack is a reference to a piece of memory in the heap.
  • friend object:
    • will point to the same stack address (004)
    • so both the me and friend object point to the same object.
    • so now even resigning friend.age will change the objects for both me and friend and will have the same values for both.

Code Snippets

Add / Removing Classes

  • good to aggregate many css properties at once.
// open modal FUNCTION
const openModal = () => {
    modal.classList.remove('hidden');
    overlay.classList.remove('hidden');
};

// close modal FUNCTION
const closeModal = () => {
  modal.classList.add('hidden');
  overlay.classList.add('hidden');
};
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment