You are on page 1of 13
@ Seven (7) Types 1. String ‘Any text” 2. Number 123.45 3. Boolean true or false 4, Null null 5. Undefined undefined 6. Symbol Symbol ("something' ) 7. Object { key: ‘value’ } + Array [1, “text”, false] = Function function name() { } @ Object ‘An object is a data type in var user = { JavaScript that is used to store a combination of dataina oe simple key-value pair. Thats it yearofBirth calculateagi Key some code These are the } keys in user object. @ Basic Vocabulary Variable Anamed reference to a value is a variable Operator Operators are reserved-words that perform action on values and variables. Examples: + - = * in === typeof = Statement 2 A group of words, numbers eS and operators that doa Note: var, const areal Keyword / reserved word valid keywordsto Any word that is part of oe ecavevarabes. the vocabulary of the Acfaonca aera Heweentteig -Programminglanguage is group of reference(s) coveredon page7 called a keyword and value(s) combined ofthis cheatsheet. (a.k.a reserved word). with operator(s), which Examples: var = * i for. resultin a single value. ai", Value Method These are the Ifakey has a 1988, values of the respective keys inuser object. function as a value, its called a method. function(){ @ Function Parameters / Arguments ‘A function is simply a bunch of code bundled in a section. This bunch of code ONLY runs when the (optional) function is called. Functions allow for organizing code into sections and code reusability. ‘A function can optionally take parameters (aka arguments). The function can then use this information within the code it has. Using a function has ONLY two parts. (1) Declaring/defining a function, and (2) using/running a function. n // Function de Thats it its just a name ation Pruners yougie toyurtneon. \_ neon oneName( arent, parand) { To: Mate your ncn Name of fun¢ a Function stati on names descriptive to what / h of code es needed Code block ee / bunch of code as needed ee any code within the cuty var a = paraml + "love" + param2; braces... }is called a “block of code’, “code return a; k . enum (optenal) ————" block or simply "block ‘function ean optioaly Y Tite foneone spitout or return’ a value - statements’ "for loops” once its invoked. Once a / Invoke (run / call) a function and other statements function returns, no further lines of code within the someName("Me", "You" use code blocks as well ———— function run. eee 7 Invoke a function Passing parameter(s) to a function (optional) Invoking, calling or running a function all mean the same At the time of invoking a function, parameter(s) thing, When we write the function name, in this case ‘may be passed to the function code. someName, followed by the brackets symbol () lke this someName(, the code inside the function gets executed. ® Vocabulary around variables and scope Variable Declaration Scope ver a; The creation of the __Thelimits in which a variable exists, var @ = “global”; variable. oe Function Farst(){ Variable nalization The outer most scope is called the Global var a = “fresh a= 12; Teil scope Pasar function second(){ Functional scope console.109(2); Any variables inside a function isin scope , Variable Assignment of the function Assigning value toa variable Lexical Environment (Lexical scope) ‘Scope chain The physical location (scope) where a The nested hierarchy of scope is console.1og(a); Hoisting variable or functions declared is ts lexical called the scope chain. The JS oenearae: Variables are environment (lexical scope) engine looks for variables in the declared at the top scope chain upwards (tits of the function ule ancestors, until found) automatically, and (1) Variables in the outer scope can be inialzed atthe time accessed ina nested scope; But variables they are run inside a nested scope CANNOT be accessed by the outer scope. (a.k.a private variables.) (2) Variables are picked up from the lexical environment. © Operators * Operators are reserved-words that perform action on values and variables. Arithmetic Relational / Comparison Operator Precedence 4 Add Greater than or equal to Given multiple operators are used in an expression, the “Operator ~. Subtract Less than or equalto Precedence" determines which operator will be executed first. The + Multiply I=. Not equal after coercion higher the precedence, the earlier it wll get executed. /.. Divide Not equal %.. Remainder Operator Associativity © Exponential Increment / Decrement Given multiple operators have the same precedence, “Associativty" +++ Postfix increment determines in which direction the code will be parsed. Assignment ~ Postfix decrement ‘Assign value See the Operator Precedence and Associativty table here: Add then assign ++. Prefix inerement nto /bittoperatortab Subtract then assign Prefix increment Multiply then assign Others @ Coercion ae Ne When trying to compare different "types', the JavaScript engine oo i attempts convert one ype int anther so it can compare the two ‘pread-operator values Equality ‘Type coercion priority order aoe Equality {4 1. String a Equality with coercion new 2. Number true - 5 4 delete 3. Boolean Conversion Gt) a +.. Convert to number Coercion in action Convert to number then negate it Does this make sense? !.. Convert to boolean then inverse it Conditional Statements Conditional statements allow our program to run specific code only if certain conditions are ‘met. For instance, lets say we have a shopping app. We can tell our program to hide the “checkout” button if the shopping cart is empty. If -else Statement: Run certain code, “if a condition is met. Ifthe condition is not met, the code in the "else" block is run (if available.) expression, and runs the code of the “case” ‘where the expression matches. The "break" keyword is used to end the switch statement, if (a> @) { switeh (expression) { case choicet aver run this code eieel( break; run this code } case choice run this code break; ‘Ternary Operator: A ternary operator returns the first value if the expression is truthy, or else retums the second value. default run this code (expression)? iffrue: ifFalse; } @ Truthy / Falsy There are certain values in JavaScript that return true when coerced into boolean, Such values are called truthy values. On the other hhand, there are certain values that return false when coerced to boolean, These values are knows as falsy values. ‘Truthy Values Falsy Values true false "text" c 2 e 72 -0 Infinity NaN -Infinity null O undefined u © Loop Statements Loops are used to do something repeatedly. For instance lets say we get a list of 50 blog posts from the database and we want to print thei titles on our page. Instead of writing the code 50 times, we would instead use a loop to make this happen. ‘Step 1: Run the initial expression, ‘Step 2: Check if condition meets. If condition meets, proceed; of else end the loop. For loop ‘Step 3: Run the code in block. dition; second-expre “ ‘Step 4: Run the second-expression. Step 5: Go to Step 2. ie oo ; step contin ite proceso while (4<3){ else end the loop. step 2: Run the code in block, } Step 3: Go to Step 1 Do while loop ‘Step 1: Run the code in block. do { Step 2: f the condition is true, proceed; or this else end the loop. ; Step 3: Go to Step 1. } while (4<3); ° ia @ Ways to create a variable There are 3 ways to create variables in JavaScript var, Let and const. Variables created with var are ver @ = “some value”; global scoped in scope ofthe function or global if declared inthe et b = “sone value"; lobal scope); Let variables are block scoped: and ons @ = “some valuc” ae const variables are like Jett plus their values j coe cannot be reassigned. @® Event Loop OP oo we alee ane ae we we we ane ae we we we we we afew we oe a, ee ~ JavaScript Engine ~ Message Queue Call Stack Lastin first-out SSS ® Browser ‘Aweb browser is a pretty advance piece of software which contains a lot of components. Many of these components are accessible to a web developer, so we can create complex web apps. At the same time a lot of components are kept out of reach of the web developer for ‘security purposes. For instance, we as web developers can get access to the users location, but we cannot get access to the user's saved passwords or browsing history. Let's see below how a browser is structured: ‘The browser contains a lot of components that a Front-End Developer may need, such as Navigator, JavaScript Engine and Dev Tools. Window Each tab of a browser is considered the window. This is the outer most container that a web-app can access. Notice: A website opened in one tab CANNOT access the window Document object of another tab. The viewport or the section Pretty cool right? where the website is displayed is. called the document of the page. @ DOM - Document Object Model ‘Query/Get Elements document querySelector(*css-selectors") document .querySelectorAll("css-selectors Old ways, and still work: document . getElement sByTagName( “elenent-nane' ) document . getElement s8yClassName( ‘class-nane' ) document .getElenent8yT¢( id") Create / clone Element. document .createElenent(“div') document .createTextNode( "some text here") node. cloneNode() node.textContent = ‘sone text here ‘Add node to document arentNode .appendChila(nodeTondd) parentNode.insertaefore(nodeToAdd, childNode) Get Element Details node nextSibLing node. firstchild node. 1astchald node.parentNode node .chi1dNodes rnode.children Events List of Events: itps//developet mozilaorg/en-S/docs/Web/Events cor google “Mozila event reference" Modify Element node.style.colo node.style.padding node.style. fontsize red! 0px", 200%: node.setAttribute( attr-name", ‘attr-value’) node. renaventtrsbute(attr-nane’) Get and Mi node.clacslict node.classList.add("class-name", ...) node.classList remove(‘class-nane', ...) node.classList.toggle(class-nane* ) node.classList .contains( ‘class-nane" ) Element Class node.classList.replace('old’, ‘nen') Remove Node parentNode. renoveChild(nodeTorenove) Hack to renove self ‘nodeToRenove .parentNode..renoveChild(nodeToRenove) node.addEventListener("event-name’, callback-function) node. renoveE ventListener( ‘event-nane Lback-function) ‘What is a "Node"? (in the context of DOM) Node: Every item in the DOM. ‘trees called a node. There are two types of node-A text node, and an element node: ‘Text Node: Node that has tex. Element Node: Node that has an element. Child Node: A node which i a child of another node, Parent Node: A node which has one or more child Descendent Node: A node which is nested deep in the tree, Sibling Node: A node that share the same parent node, ® Auto Inherited Properties When you create a value in JavaScript, certain properties are automatically inherited by this value. This magic happens because every type has a constructor with a special property called prototype. All ‘methods on the prototype gets automatically inherited by the new value created for that type. Take a look at some of of these methods on the right. Bu Objects JavaScript gives us a ton of useful built-in objects to make our lives easier. The Date and Math objects are very useful on a regular basis. Take a look at some of their features on the right. const thing = String Google char) inde: star endst split slict Math at() at) x0F() eith() Hith() ) e() some text"; ing to fi he doc Google MozileMath'to find the docs Math. wath. Math. ath, Math. Math. Math. pow(2, 8) sqrt(16) min(7, 8, 6) nax(7, 8, 6) loor(123.45) coil(123.45) round(123.48) random() 8 8 24 Rea any filter() Number map() ani) eat tstrecinln() pe patina m0 stice() splice() ; recat) rt foreach) bate tae d.getFullvear() 4.getonth() Date.now() @ Promise What is a Promise? Promise is an object that provides a useful construct when dealing with asynchronous tasks. A promise is called a “Promise” because it guarantees it will run upon success or failure of that task. Working with a promise consists of two parts; (A) Creating a promise, and (8) Using a promise. // (A) Create a promise const p = new Promise((resolve, reject)=>{ // Do some async task setTimeout(()=>{ if (condition) { resolve( ‘Successful login’) ; } else { reject('Login failed’); } }, 2000) y) What is an Asyne task? ‘An async task is one in which a third-party process is doing the task. Examples: - Requesting/sending data to a database = Requesting/sending data via HTTP protocol = Working with the file system of the computer // (B) Using a promise p.then((res)=>{ console. 1og(res) ») -catch((err)=>{ console. log(err) +) Note: 90% of the time you will be working with pre-existing promises. The step of "Creating a promise” would be done for yyou either by a library, framework or environment you are Using. Examples of promises: fetch ® ‘this’ keyword ‘The this keyword is used inside a function. The this keyword is merely a reference to another object. What the this keyword refers to depends on the scenario or the way the function is implemented. Here are the 3 scenarios to remember: ‘Scenario #1: this inction The this keyword points to global object. ‘Scenario #2: this it The this keyword points to the object the method is in. ‘Scenario #3: When function is run with call,bind or apply When a function is called using the .call(param) bind(param) or .apply(param) ‘method, the first param become the object that the this keyword refers to Important Note: In the browser, global is the window object. In Node js, global is the global object. var name = "Fatema"; function fun(){ some code here console.1og( this.name) ; const user = { name: "Marium", yearOfBirth: 1999, caloage: function(){ const currentYear new Date()).getFullyear(); return currentYear - this.yearOfBirth; + } fun(); this’ is global. Logs "Fatema’ user.calcAge(); // ‘this’ is the user object fun.call(user); // ‘this’ is the user object. Logs "Mariun’ © Constructor Defining a Constructor Rule of thum What is a constructor? ‘unetion Car 1% a a) i In JavaScript, aconsttuctoris a special 7 uNe10n Car(make, model, year) ise Sooeton function that acts as a mold to create ee ecko new objects this.model = model; 8) Set methods inside ‘There are numerous built-in constructors eae oo Claes pert in JavaScript, such as String, Number, a Promise, Date, Array, Object, and many this.setMiles = function(miles){ more. this.miles = miles sew" keyword ve . . return miles; The new keyword is fe can create cur own custom " used to reste a new constructors if need be. ) object (instance) from. the constructor. A great place to use a constructor is we constructo when you are creating multiple objects of tram o en! aren the same kind const art = new Car(*Toyota’, ‘Prius’, 2016); "prototype" property prototype is a special property on every object. Properties (methods or values) Car.prototype.age = function(){ attached to the return (new Date()).getFullYear() - this.year prototype property get inherited to every (2) Using a constructor > cabo instance of the with the "no" keyword an constructor. cart.age(); // 2 “There are two parts to working with a const car2 = new Car(*Hyundai', ‘Sonata’, 2018); constructor: (1) Defining a constructor When creating a custom constructor

You might also like