Created
January 7, 2022 02:49
-
-
Save Doaxan/024e3278316990becae1451a448326bb to your computer and use it in GitHub Desktop.
JavaScript Cheatsheets
-
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>- JavaScript files have the file extension
.js. - Put name of script file in the
srcattribute 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>// 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()'// 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 - 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); // 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// 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.`);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. 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")
}// 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 & resultsconst age = 19;
if (age >= 18){
console.log(`old enough`)
} else {
console.log(`too young`)
}// &&
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); // falseconst 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");
}// 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");
}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 (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]);
}let n = 0
while(true){
console.log(n);
n += 1;
if(n == 11)break;
}*'use strict';: place this code at the beginning of any js file to have js warn us of errors.
// can be called before being defined.
function calcAge1(birthYear) {
return 2022 - birthYear;
}// can not be called before being definde.
const calcAge2 = function (birthYear) {
return 2022 - birthYear;
}
console.log(calcAge2(2000));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`;
};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
}// 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);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 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";// 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());- 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 ofWeb API's.Web APIare likelibrariesthat browsers implement and that we can access from our JS code.DOMallows us to access a node’s attributes, such as itsclass,id, andinline style.
documentis the Entry point, that's why we start the commanddocument.querySelector()with the worddocument.document.bodyto access the body.document.headto access the head..innerHTMLgets or sets the HTML or XML markup contained within the element..innerHTMLproperty can also add any valid HTML, including properly formatted elements.
document.body.innerHTML = "Hello World"will print "Hello World" to the page.document.body.innerHTML = "<h2>heading</h2>";assigns anh2element as a child inside the<body>ele.
.querySelector();returns 1st Element that matches selector, or group of selectors. If no matches,nullis returned.document.querySelector("p");get the first<p>element in the document.document.querySelector(".example");get the first element in the document withclass="example".document.querySelector("#demo").innerHTML = "Hello World!";change the text of an element withid="demo".document.querySelector("p.example");get the 1st<p>ele in the doc withclass="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.
document.getElementById('bio').innerHTML = 'The description';this is another option to select by ID.
var x = document.querySelectorAll(".example");get all elements in the document withclass="example".- Add an
even listenertoSelectAll:
for (let i = 0; i < x.length; i++){
x[i].addEventListener("click", function(){ ... do smth ...});
}.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 theadd(),remove(),replace(), andtoggle()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");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 aselement.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>className propertyis 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.
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);document.querySelector("#demo").innerHTML = "Hello World!";change the text of an element withid="demo".document.querySelector(".myclass").textContent = "my-new-content";not sure how it's diff than.innerHTML..styleproperty of a DOM element provides access to the inline style of that HTML tag.element.style.propertyformat, with thepropertyrepresenting 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';backgroundColorunlike CSS, the DOMstyleproperty does not implement a hyphen such asbackground-color, but rather camel case notation.
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);});.onclickproperty 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' };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 theeventinto oureparam. Example:
document.addEventListener('keydown', function (e) {
if (e.key === 'Escape' && !modal.classList.contains('hidden')) {
closeModal();
}
});- JS does not have to manage hardware, memory such as:
CPU / Ram
- Low level languages such as
CorC++need to manage memory. - JS use
abstractionsto manage hardware / memory. - The downside is that JS will never be as fast as low level languages.
garbage collectionmakes it possible for JS developer to have to worry about memory.GCstands 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.
machine codeis the zeros and ones that the cpu understand.interpreter / compilerboth turn our high level code to machine code.JSuses and interpreter.
JS Engineis simply a computer program that executes JS code.- Most browser have their own JS engine.
Google V8 engineis the most common JS engine.- the
V8engine powersgoogle chrome&NodeJS. - other browsers have their own
JS engines.
- the
- Every JS engine has:
- 1.
call stack - 2.
heap
- 1.
Call Stackis where our code is executed.Call Stackusesexecution context.
Heapis an unstructured memory pool.Heapcontains all the objects our program need.
Compilationthe entire code is converted intomachine codeat 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.
Interpreterruns through the source code & execute it line by line.- Read & Execute at the same time.
- Code still needs to be conversted to
machine codebut it happens right before being executed, not ahead of time.
Interpreterare slower thanCompilers.- JS was purely an
interpretedlanguage before.
Modern JSuses a mix betweencompilation&interpretation.- this is called
just-in-time compilation.
- this is called
JITSteps: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.
- Step 1:
parsing the codemeans the engine reads the code.ASTis the Abstract Syntax Tree is the Data Structure where the parsing is places.
- Step 2:
compilationconverst code to machine code. - Step 3:
executioncode gets executed right away.- that is the
Just-In-TimeCompilation part. executionhappen in thecall stack. In the background the code is still being optimized & recompiled.
This constantoptimization& update is what makes modern JS Engine such as theV8so fast.
- that is the
runtimewe can imagine it as a big container that includes all the things we need to use JS, in this case in the browser.runtimeincludes theJS Engine, plus theWeb APIsandCallback Queue.Web APIare functionalities provided to the engine, but not part of the JS language.Callback queuecontains all the callback functions that are ready to be executed.
paradigmAn approach & mindset of structuring code, which will direct your code style & technique.- 3 popular paradigms are:
-
- Procedural Programming.
-
- Object Oriented Programming (OOP).
-
- Functional Programming (FP).
-
paradimnscan also be clasiffied asimperativeordeclarative.
while many languages are only procedural or OOP, or functional, JS does all of it.
- This means that almost everything in
JSis anobject. primitive valuessuch as numbers, strings.. are the exception to beingobjects.
- In a language with
first-class functions, functions are simplytreated as variables. - We can pass them into other functions, & return them from functions.
- 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.
concurrency modelis 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. threadis a set of instructions that is executed in the CPU.- So what do we do if there is a long-running task ? (next section).
- By using an
event loopwe take long-running tasks, executes them in the "background", and puts them back in the main thread once they are finished.
Execution ContextEnvironment in which a piece of JS is executed. Stores all necessary info for some code to be executed.Execution ContextJS code always run inside an Execution Context.Execution ContextcontainsYour Codeand:this <keyword>except for arrow functions.Scope Chain.Variable Environment.let, const, and vardeclarations.functions.argument objectsexcept for arrow functions.
- Imagine you order a
pizzato be delivered. - The
pizzarepresents thecodeyou write. - The
pizzawill come in aBOXthat has the Pizza, Cutlery, Napkins, and Receipt. - The
BOX=EXECUTION CONTEXT.
Global Execution Contextthere is always only one for each program.
Other Execution Contextsare created for functions.
Call Stackis composed of all theexecution contexts.Call Stackis where theexecution contextsget stacked on top of one another to keep track of where we are in the execution process.
scopinghow our program's variables areorganized&accessed.lexical scopingscoping is controlled byplacementof functions & blocks in the code.scope of a variableregion of our code where a certain variable can beaccessed.scopeis the space or environment in which a certain variable isdeclared.global scopefunction scopeblock scope
varfunction scope but not block scopes, so we can access then outside blocks.letif declared inside a block, only accessible inside the block.constif declared inside a block, only accessible inside the block.
hoistingmakes 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 thevariable envionment object.
thisspecial variable that is created for every execution context (every function).thistakes the value (points to) the "owner" of the function in which thethiskeyword is used.thisis 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 (lexicalthis ) }. - Event Listener
this= { DOM element that the handler is attached to }.
thisdoesNOTpoint to the function itself, and alsoNOTto the variable envionment of the function.
JS Engineis composed of:Call StackHeap
Primitivesare stored in thecall stack.
NumberStringBooleanUndefinedNullSymbolBigInt
'use strict';
let age = 30;
let oldAge = age;
age = 31;
console.log(age);
console.log(oldAge);agevariable:Identifier: age.- The
identifierage points to the address001and not to the value30.
- The
Address: 0001.Value: 30.
oldAgeis set to equalageso at first it will also point to the address001.- but once we set
ageto a different value (31), then age will point to a new different address, maybe002.
Objectsare all stored in thememory heap.- stored in the execution context in which they are declared.
Object literalArraysFunctionsMany more ...
'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 = 40meobject:meobject will also have an address (D30F) and a value ({name: "Mike", age: 30}).- but
mewill point to an address in theStack(004) which holds the address of the value in theheap(D30F). - so the memory in the call stack is a
reference to a piece of memory in the heap.
friendobject:- will point to the same stack address (
004) - so both the
meandfriendobject point to the same object. - so now even resigning
friend.agewill change the objects for bothmeandfriendand will have the same values for both.
- will point to the same stack address (
- 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