Docsity
Docsity

Prepare for your exams
Prepare for your exams

Study with the several resources on Docsity


Earn points to download
Earn points to download

Earn points by helping other students or get them with a premium plan


Guidelines and tips
Guidelines and tips

JavaScript Cheatsheet: Understanding Variables, Objects, Functions, and Operators, Study Guides, Projects, Research of Engineering

A comprehensive cheatsheet on JavaScript, covering the basics of variables, expressions, operators, objects, functions, and conditional statements. It includes explanations of primitive types, coercion, truthy and falsy values, and various ways to create variables. The document also touches upon the browser environment and built-in objects in JavaScript.

Typology: Study Guides, Projects, Research

2018/2019

Uploaded on 03/22/2022

usa-vpn
usa-vpn 🇮🇳

4

(1)

3 documents

1 / 13

Toggle sidebar

Related documents


Partial preview of the text

Download JavaScript Cheatsheet: Understanding Variables, Objects, Functions, and Operators and more Study Guides, Projects, Research Engineering in PDF only on Docsity! Note: var, let & const are all valid keywords to declare variables. The difference between them is covered on page 7 of this cheatsheet. 2 Basic Vocabulary Expression A reference, value or a group of reference(s) and value(s) combined with operator(s), which result in a single value. Variable A named reference to a value is a variable. Keyword / reserved word Any word that is part of the vocabulary of the programming language is called a keyword (a.k.a reserved word). Examples: var = + if for... Operator Operators are reserved-words that perform action on values and variables. Examples: + - = * in === typeof != ... Statement A group of words, numbers and operators that do a task is a statement. var a = 7 + "2";{ { 1 Seven (7) Types 1. String 2. Number 3. Boolean 4. Null 5. Undefined 6. Symbol 7. Object - Array - Function "Any text" 123.45 true or false null undefined Symbol('something') { key: 'value'} [1, "text", false] function name() { } { S ix P ri m it iv e T y p e s var user = { name: "Aziz Ali", yearOfBirth: 1988, calculateAge: function(){ // some code to calculate age } } { Key These are the keys in user object. Value These are the values of the respective keys in user object. Method If a key has a function as a value, its called a method. 3 Object An object is a data type in JavaScript that is used to store a combination of data in a simple key-value pair. Thats it. "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 1< >♥ iLoveCoding 4 Function A function is simply a bunch of code bundled in a section. This bunch of code ONLY runs when the function is called. Functions allow for organizing code into sections and code reusability. Using a function has ONLY two parts. (1) Declaring/defining a function, and (2) using/running a function. // Function declaration / Function statement function someName(param1, param2){ // bunch of code as needed... var a = param1 + "love" + param2; return a; } // Invoke (run / call) a function someName("Me", "You") Name of function Thats it, its just a name you give to your function. Tip: Make your function names descriptive to what the function does. Code block Any code within the curly braces { ... } is called a "block of code", "code block" or simply "block". This concept is not just limited to functions. "if statements", "for loops" and other statements use code blocks as well. Return (optional) A function can optionally spit-out or "return" a value once its invoked. Once a function returns, no further lines of code within the function run. Invoke a function Invoking, calling or running a function all mean the same thing. When we write the function name, in this case someName, followed by the brackets symbol () like this someName(), the code inside the function gets executed. Passing parameter(s) to a function (optional) At the time of invoking a function, parameter(s) may be passed to the function code. Parameters / Arguments (optional) A function can optionally take parameters (a.k.a arguments). The function can then use this information within the code it has. "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 2< >♥ iLoveCoding if (a > 0) { // run this code } else if (a < 0) { // run this code } else { // run this code } switch (expression) { case choice1: // run this code break; case choice1: // run this code break; default: // run this code }(expression)? ifTrue: ifFalse; If -else Statement: Run certain code, "if" a condition is met. If the condition is not met, the code in the "else" block is run (if available.) 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. Switch Statement: Takes a single expression, and runs the code of the "case" where the expression matches. The "break" keyword is used to end the switch statement. There are certain values in JavaScript that return 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. Ternary Operator: A ternary operator returns the first value if the expression is truthy, or else returns the second value. 8 Conditional Statements Truthy Values true "text" 72 -72 Infinity -Infinity {} [] Falsy Values false "" 0 -0 NaN null undefined 9 Truthy / Falsy "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 5< >♥ iLoveCoding for (initial-expression; condition; second-expression){ // run this code in block } 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 their titles on our page. Instead of writing the code 50 times, we would instead use a loop to make this happen. while (i<3){ // run this code in block i++; } do { // run this code in block i++; } while (i<3); Step 1: Run the initial expression. Step 2: Check if condition meets. If condition meets, proceed; or else end the loop. Step 3: Run the code in block. Step 4: Run the second-expression. Step 5: Go to Step 2. Step 1: If the condition is true, proceed; or else end the loop. Step 2: Run the code in block. Step 3: Go to Step 1. Step 1: Run the code in block. Step 2: If the condition is true, proceed; or else end the loop. Step 3: Go to Step 1. For loop While loop Do while loop 10 Loop Statements "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 6< >♥ iLoveCoding Event Loop DOM Events Timer Process HTTP Process Third-Party Process JavaScript Engine Global Ex. Context Execution Context Execution Context Call Stack Last-in - first-out Task Task Task Message Queue 12 Event Loop There are 3 ways to create variables in JavaScript: var, let and const. Variables created with var are in scope of the function (or global if declared in the global scope); let variables are block scoped; and const variables are like let plus their values cannot be re-assigned. var a = "some value"; // functional or global scoped let b = "some value"; // block scoped const c = "some value"; // block scoped + cannot get new value 11 Ways to create a variable "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 7< >♥ iLoveCoding 16 Built-in Objects Date Google 'Mozilla Date' to find the docs const d = new Date('9/17/1988'); d.getDay() d.getFullYear() d.getMonth() Date.now() Milliseconds since Jan 1, 1970 Math Google 'Mozilla Math' to find the docs Math.pow(2, 3) // 8 Math.sqrt(16) // 4 Math.min(7, 8, 6) // 6 Math.max(7, 8, 6) // 8 Math.floor(123.45) // 123 Math.ceil(123.45) // 124 Math.round(123.45) // 123 Math.random() // 0.45.. 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. Full list of builtin objects in JavaScript visit https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects 15 Auto Inherited Properties String Google 'Mozilla String' to find the docs .concat() .charAt() .indexOf() .startsWith() .endsWith() .split() .slice() Number Google 'Mozilla Number' to find the docs .toFixed() .toPrecision() .toString() Boolean Google 'Mozilla Boolean' to find the docs .toString() Array Google 'Mozilla Array' to find the docs .filter() .map() .find() .every() .some() .sort() .slice() .splice() .reduce() .forEach() 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. const thing = "some text"; const num = 123.45; "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 10iLoveCoding< >♥ 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 (B) Using a promise. 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 17 Promise 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 // (B) Using a promise p.then((res)=>{ console.log(res) }) .catch((err)=>{ console.log(err) }) // (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) }) "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 11iLoveCoding< >♥ 18 'this' keyword var name = "Fatema"; function fun(){ // some code here console.log(this.name); } const user = { name: "Marium", yearOfBirth: 1999, calcAge: 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 "Marium" Scenario #1: this inside a function The this keyword points to global object. Scenario #2: this inside a method 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. 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: Important Note: In the browser, global is the window object. In Node.js, global is the global object. "Don't just learn JavaScript - Become a Full-Stack JavaScript Developer" https://iLoveCoding.org iLoveCoding JavaScript Cheatsheet Learn JavaScript Correctly (Video course) https://ilovecoding.org/courses/js2 Page 12< >♥ iLoveCoding
Docsity logo



Copyright © 2024 Ladybird Srl - Via Leonardo da Vinci 16, 10126, Torino, Italy - VAT 10816460017 - All rights reserved