You are on page 1of 14
Beginners to Advanced PDF Download @ Basic Vocabulary Fi Variable Operator iL piind eee Anamed reference to Operators are reserved-words that 2. Number 2 oe. perform action on values and variables. 3. Boolean z Examples: = * in === typeof = 4. Null 5. Undefined s (Seaantel v. group of words, & SSymbol = ‘numbers and a ‘operators that do a 7. Die valle: task is a statement. ie 3 Keyword / reserved word \ + Array » false] Anyword thatispartofthe Expression Function n name()/{ vocabulary of the programming —_A reference, value or a group language iscalledakeyword of reterence(s) and value(s) (ak.a reserved jword). ‘combined with operator(s), ® Examples: var = result in a single value, An object is datatype in nero “JavaScript that is used to store sae aE valle method ‘ combination of data ina 2 ania ae itatey Han a simple key-value pair, Thats it. Seale values of the funetion as a caleulateage: function(){ respective keys vale, its called // some code to ulate age in user object. ‘a method. key ) These are the keys in user object. , @ r Parameters / Arguments ‘Auction is simply a bunch of code bundled in a section. This bunch of code ONLY runs when the (optional) funetion is called. Functions allow for organizing code into sections and code reusability, ‘A function can optionally take parameters (ak.a arguments). The function can then use this information within the code it has, Using 2 function has ONLY two parts. (1) Declaring/defining a function, and (2) using/running a function, Name of function // Function dé@laration. Thats it its just a name Jougietoyeurtneton “function ganetiane (bara i: Make your uncon m2: braces (... }is called a names descriptive to what / bunch of code as needed — the function does. t ” ra s{parami + “love” + “block of code’, “code ee rece, ea ch a This concepts not just asctaetrs tat limited to functions." Ly statements”, “for loops" Sues nel inoaea oie 1/ Invoke (run / cal¥y’a function andottundatements function returns, no further cru 7 1d other statement: lines of code within the someName("Ne", “You ——< — function run Serene Code block Any code within the curly Use code blocks as wel evoke atnction "2 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. Name, followed by the brackets symbol (like this ame), the code inside the function gets executed @® Vocabulary around variables and scope console.1og(a); vara Variable Declaration The creation of the variable. Variable Initialization The initial assignment of value toa variable. Variable Assignment Assigning value to a variable. Hoisting Variables are declared at the top of the function automatically, and initialized at the time they are run. ‘Scope ‘The limits in which a variable exists. Global scope ‘The outer most scope is Called the Global scope. Functional scope ‘Any variables inside a function is if scope of the function, Lexical Environment (Lexical scope) The physical location (scope) where a variable or function is declared is its lexioal environment (lexial scope) bles in the outer scope can be accessed ina nested scope; But variables inside @ nested scope CANNOT be accessed by the outer scope. (a.k private variables.) (2) Variables are picked up from the lexical ‘environment. var a= "global"; function first(){ var a fresh"; function second(){ console. 1og(a) ; ‘Scope chain The nested hierarchy of scope is called the scope chain. The JS tengine looks for variables in the scope chain upwards (it its ancestors, until found) Ful ist of JavaSeritoperatorshtps/developar.ma © organ. /doce/Weh/JavaScriFlerence/Operatars Operators are reserved-words that perform action on values and variables, Arithmetic Relational / Comparison +. Add >=... Greater than or equal to Subtract <=. Less than oF equal to Multiply |=. Not equal after coercion /.. Divide Iss Not equal %.. Remainder “Exponential Increment / Decrement “++ Postfix increment Assignment = Postfix decrement Assign value ‘Add then assign ‘++, Prefixincrement Subtract then assign =. Prefix increment ‘Multiply then assign others. Logical typeof I. Or instanceof 88. And tai sspread-operator Equality td Equality with coercion new delete Conversion LB tol +. Convert to number Convert to number then negate it !.. Convert to boolean then inverse it Operator Precedence Given multiple operators are used in an expression, the “Operator Precedence" determines which operator will be executed first. The hhigher the precedence, the earlier it will get executed Operator Associativity Given multiple operators have the same precedence, “Associativity” determines in which direction the code will be parsed, ‘See the Operator Precedence and Associativity table here: bitty opatortable When trying to compare different "types", the JavaScript engine ‘attempts to convert one type into another so it can compare the two values ‘Type coercion priority order: Toehg 2 pare 2. Number true- 5 // -4 3. Boolean Coercion in action Does this make sense? 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) af (a> 0) 4 J/ run this code } else af (a < 6) { J] run this code } else { // un this code Temary Operator. A ternary operator returns the first valve ifthe expression is truthy, or else returns the second value, (expression)? iftrue: iffalse; Switch Statement: Takes & single expression, and runs the code of the "case" where the expression matches. The *bre: keyword is used to end the switch statement, switch (expression) { ease choice 71 Pity His code! break; choicel: 1/ run this code 11 run this code © Truthy / Falsy ‘There are certain values in JavaScript that retum true when coerced into boolean. Such values are called truthy values. On the other hand, there are certain values that return false when coerced to boolean. These values are knows as falsy values. © Loop Statements Loops are used to do something repeatedly. For instance lets say we get alist of 50 blog posts from the database and we want to print their titles on our page. Instead of writing the code 60 times, we would instead use a loop to make this happen. ‘Step 1: Run the intial expression. Step 2: Check i condition meets. condition meets, proceed; o ele end the io For loop i Step 3: Run the code in block for (Anitial-expression; condti@My seoondbe-Dression)y eee /1 run this code in block ‘Step 4: Fun the second-expression ‘Step 5: Go to Step 2. While loop a Step 1: f the condition is true, proceed; or while (4«3){ else end the loop eels oa codes Sask: 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: ifthe consition is tue, proceed; or I run this code in block ‘else end the loop. att } while (1<3); ‘Step 3: Go to Step 1 @ Ways to create a variable There are 3 ways to create variables in JavaScript: Jet and const. Variables created with var are 2 = “some value functional or global scoped in scope of the function (or global if declared in the global scope); 1e* variables are block scoped; and onst variables are like Let plus their values ‘cannot be reassigned. @® Event Loop block scoped + cannot get new value ee aa eee ote os ~1 — 7 avaScript Engine ‘ Third-Party, Process HTTP Process Timer Process DOM Events: Call Stack Lastin- first-out ® ‘A.web 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 user's 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, hetpsi/- container that a web-app Notice: A website opened inone tab CANNOT access the window object of another tab. Pretty cool right? Document ‘The viewport or the section where the website is displayed is called the document of the page. Query/Get Elements Preferred way: docunen lerySelector(‘css-selectors"] ALL(*ess-selectors’, 01d ways, and stil work: agName(' element-nane*) assNane( ‘class-nane") id") Create / clone Element docunent ,createELenent(‘div") reateTextNode("some text here) eNode() ntent = ‘some text here ‘Add node to document ParentNode. parentNode Get Element Details Events node .addéventListen List of Events: tps (Cevent-nane ner("event-nane attr-value") joveAttribute( ‘attr-name' ) Get and Modify Element Class ssLietadd(class-nané”, ...) fenove(“clags-nane", ...) new") parent / Hack to renove self nodeToRenove.parentNode. resoveCht ceallback-function) ‘albeck-function) jacra/ensS/docs/eb/Events or google ‘Mozila event reference” What is a "Node"? {inthe context of DOM) Node: Every item in the DOM ‘tees called a node. There ‘are two types of node-A text node, and an element node: ‘Text Node: Node that has text Element Node: Node that has ‘an element. Child Node: & node which isa child of another node. Parent Node: Anode which has one or more child Descendent Node: A node ‘which is nested deep in the tree. ‘Sibling Node: Anode that share the same parent node. © Auto Inherited Properties When you create a value in JavaScript, certain properties are automatically inherited by this value. const thing = This magic happens because every String type has a constructor with a special Goosie Moz property called prototype. All ‘coneat() ‘methods on the prototype gets ceharat() automatically inherited by thenew ——.index0f() value created for that type. etartenath(), Take a laok at some of of these ‘endsith() methods on the right. eplit() slice() Built-in Objects JavaScript gives us a ton of useful builtin 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. Math Math.pow(2, 3) Nath. sqrt(16) Math.min(7, 8, 6) Math.max(7, 8, 6) Math. floor(123.45) Matn.co1(128.45) Math. round( 7123.45) math. randoa() Sting’ t find the de tf but objects in Jovan ve its dewlopetme Google Mozila Mat to find teoos wa U6 we W112 const num = 123.45; Number eagle Mozilla Number't find the docs Horixec() -tePréeieson() tostrang() Boolean Goaglé Merila Boolean’ to find the doce testrang() Google MozilaDat'to find the doce ceils Web JavaScrt(he Array Goagle Mozilla Anay 0 falter() map) Find() every() some() sort() slice() splice() reduce() for€seh() Aiba const d = new Date('9/17/1988"); 4.getday() d.getFullvear() d.gettonth() Dave.now() HiLLisecon 1970 @ 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 un upon success oF 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)=>{ 1/ Do some async task setTimeout (()=>{ if (condition) { resolve(’Successful login’); } else { reject(‘Login failed’); y }, 2000) ») What is an Async 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 {7 (B) Using a promise péthen((res)=>{ console. log(res) DD) seateh((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 you 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 var name = "Fatena”; keyword is merely a reference to another object. function fun(){ What the this keyword refers to depends on the scenario or the way the function is implemented. Here are the 3 scenarios to remember. omige (this-name) ; , kgsome code here #1 thi The this keyword points to global object. const user = { ame: “Marium”, ta rence cer yearOfBirth: 1999, The this keyword points tothe object the r+ ee: ee const currentYear = (new Date()).getrullvear(): ‘Scenario #3: When functions run with return currentYear - this.year0fBirth: call, bind ocapply , When a function is called using the ) .cali(param) .bind(param) or apply(param) ‘method, the first param become the object thatthe this keyword refers to. fun(); // “this' is global. Logs “Fatena user.caleage(); // ‘this’ is the user object fun.call(user); // "this' is the user object. Logs "Marium Important Note: In the browser, global is the window object. In Node, global is the global object. ® 11 Defining a Constructor as What is a constructor? Rule of thumb: In JavaScript, a constructor is a special aoe a aS Leeeathe function that acts as a mold to create make; new objects. = model; 8) Set methods inside = year; the prototype ‘There are numerous builtin constructors property in JavaScript, such as String, , Date, Array, Object, and many netion(miles){ more, 1 6 = miles new" keyword return miles; ‘The new keyword is We can create our own custom > Used to create anew constructors if need be. 5 object (instance) from the constructor. A great place to use a constructor is when you are creating multiple objects of 1/ Using a cong rustor ‘the same kind. @ property prototype is a special property on every object. Properties, (methods or values) : attached to the » Oe prototype property Y « J get inherited to every (2) Using a constructor > dehes instance ofthe with the "new" keyword eT constructor Or 2 = newhcar(‘Toyota’, ‘Prius*, 2016); = new ar("Hyundas', ‘Sonata’, 2018); There are two parts to working with a constructor: 11 Adding method to the constructor prototype (1) Defining a constructor When creating a custom constructor

You might also like