└── README.md /README.md: -------------------------------------------------------------------------------- 1 | # General Javascript Documentation Standards & Naming Conventions. 2 | Bonus: Small Introduction to JavaScript and ES6(ECMAScript2015 - used in ReactJS and React-Native platforms. ES6 is almost fully compatible with most browsers. [Check here for compatability](https://kangax.github.io/compat-table/es6/) 3 | 4 | ### Good JavaScript Resources: 5 | 6 | [Mozilla Developer Network](https://developer.mozilla.org/en-US/docs/Web/JavaScript) 7 | 8 | 9 | [W3Schools](https://www.w3schools.com/js/default.asp) 10 | 11 | 12 | ### Good React Resources: 13 | [Facebook's React-Native Docs](https://facebook.github.io/react-native/docs/getting-started) 14 | 15 | [React-Native DOM for Web](http://reactnative.com/react-native-dom/) 16 | 17 | [RN Tester](https://rntester.now.sh/) 18 | 19 | [RNWeb Component, APIs, and Example Apps](https://necolas.github.io/react-native-web/storybook/?selectedKind=Components&selectedStory=ActivityIndicator&full=0&addons=0&stories=1&panelRight=0) 20 | 21 | [Zeplin](https://zeplin.io/) 22 | 23 | [UIZoo](https://myheritage.github.io/UiZoo.js/) 24 | 25 | [Redux / Flux Q&A](https://stackoverflow.com/questions/32461229/why-use-redux-over-facebook-flux) 26 | 27 | [React SketchApp from AirBnB](https://github.com/airbnb/react-sketchapp) 28 | 29 | ### React-Native-Web (Compatability React-Native 0.55, current= 0.56) 30 | 31 | [React-Native-Web Docs](https://github.com/necolas/react-native-web/blob/master/packages/website/guides/getting-started.md) 32 | 33 | ### React-Native-Web, web-specific UI patterns 34 | [Links](https://codesandbox.io/s/53r88k5opx) 35 | 36 | [Hover styles](https://codesandbox.io/s/o9q8vy70l5) 37 | 38 | [Root element styles](https://codesandbox.io/s/52x1871vjl) 39 | 40 | # Table of Contents: 41 | ### 1. Commenting & Documentation *(read: styleguide)* 42 | 43 | ### 2. General JavaScript Intro + Best Practice 44 | - JavaScript Keywords 45 | - General Guidelines 46 | 47 | 1. Avoiding Global Namespace 48 | 49 | 2. Declare Functions and Variables 50 | 51 | 3. Declare Expressions cleanly 52 | 53 | 4. Beware of JavaScript Type Conversion 54 | 55 | 5. Comparison Operators, Confusion, and You 56 | 57 | ### 3. ES6 Syntax and Modularizing the React Workspace 58 | - Modules and Grouping Components 59 | 60 | ### 4. Summary and Important React Specific Notes 61 | 62 | # 1. Commenting & Documentation / StyleGuide 63 | 64 | Commenting should describe each function and purpose, but not make the function more confusing. You are describing functionality, not giving your life story. 65 | P.S. Don't be afraid of whitespace 66 | 67 | ### Variable Names: 68 | - **camelCase** for identifier names (variables and functions). 69 | - All names start with a **lowercaseLetter**. 70 | 71 | ### Spaces Around Operators: 72 | Always put spaces around operators ( = + - * / ), and after commas: 73 | 74 | #### Examples: 75 | ```js 76 | var x = y + z; 77 | var values = []; // initialize array first 78 | values.push("Volvo", // then add values 79 | "Saab", 80 | "Fiat" // NOTE! No trailing Comma. Valid 81 | ); // JSON does not use trailing commas 82 | // Trailing Commas will crash IE8 83 | console.log(values); // result: ["Volvo", "Saab", "Fiat"] 84 | ``` 85 | 86 | 87 | ## General Rules for Statements: 88 | 89 | - Put the opening bracket at the end of the first line. 90 | - Use one space before the opening bracket. 91 | - Put the closing bracket on a new line, without leading spaces. 92 | - Do not end a complex statement with a semicolon. 93 | 94 | ### Functions: 95 | ```js 96 | function toCelsius(fahrenheit) { 97 | return (5 / 9) * (fahrenheit - 32); 98 | } 99 | 100 | // es6 arrow function: 101 | const toCelsuis = f => (5 / 9) * (f - 32); 102 | ``` 103 | 104 | Small note on the difference in declarations: 105 | the arrow function doesn't need parenthesis because there is only one parameter and no curly braces because we are only returning a value. If you have more than one parameter you will need parenthesis (ie. (p1, p2) =>). or no parameters (ex. x = () => {} 106 | 107 | If you have operations to complete within the function, you will need to have curly braces AND a return statement 108 | ```js 109 | const example = (name, title) => { 110 | var year = new Date().getFullYear(); 111 | return 'Hello ' + title + ' ' +name + ' the year is ' + year; 112 | } 113 | ``` 114 | 115 | the *function declaration* (first one) can be accessed anywhere in the top of their scope. Simply put, if you have a function declaration after content that uses it, it is OK because it will be hoisted. However, with arrow functions, there is a top-to-bottom flow that will not allow you to utilize your functions this way. We will get more in depth on scope later with **closures** 116 | 117 | ### Loops: 118 | ```js 119 | for (i = 0; i < 5; i++) { 120 | x += i; 121 | } 122 | ``` 123 | 124 | ### Conditionals: 125 | ```js 126 | if ( time < 20 ) { 127 | greeting = "Good day"; 128 | } else { 129 | greeting = "Good evening"; 130 | } 131 | ``` 132 | 133 | ## Object Rules 134 | 135 | General rules for object definitions: 136 | 137 | - Place the opening bracket on the same line as the object name. 138 | - Use colon plus one space between each property and its value. 139 | - Use quotes around string values, not around numeric values. 140 | - Do not add a comma after the last property-value pair. 141 | - Place the closing bracket on a new line, without leading spaces. 142 | - Always end an object definition with a semicolon. 143 | 144 | ### Example 145 | ```js 146 | var person = { 147 | firstName: "John", 148 | lastName: "Doe", 149 | age: 50, 150 | eyeColor: "blue" 151 | }; 152 | ``` 153 | 154 | ## Naming Conventions 155 | 156 | - Variable and function names written as **camelCase** 157 | - Constants (like Pi) written in **PascalCase** 158 | - Classes written in **PascalCase** 159 | - Hyphens can be mistaken as subtraction attempts. Hyphens are NOT allowed in JavaScript names. 160 | 161 | 162 | #### If you still want/ need more info on javascript specific content please reference the [MDN Dev Guide](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types) 163 | 164 | # 2. JavaScript General Guidelines 165 | 166 | ## Javascript Keywords 167 | 168 | ### [Link](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Lexical_grammar#Reserved_keywords_as_of_ECMAScript_2015) 169 | ### Reserved keywords as of ECMAScript 2015 170 | (Hover over a keyword to learn more about it ) 171 | 172 | - [`break`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/break "The break statement terminates the current loop, switch, or label statement and transfers program control to the statement following the terminated statement.") 173 | - [`case`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch "The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.") 174 | - [`catch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch "The try...catch statement marks a block of statements to try, and specifies a response, should an exception be thrown.") 175 | - [`class`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class "The class declaration creates a new class with a given name using prototype-based inheritance.") 176 | - [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const "The source for this interactive example is stored in a GitHub repository. If you'd like to contribute to the interactive examples project, please clone https://github.com/mdn/interactive-examples and send us a pull request.") 177 | - [`continue`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/continue "The continue statement terminates execution of the statements in the current iteration of the current or labeled loop, and continues execution of the loop with the next iteration.") 178 | - [`debugger`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/debugger "The debugger statement invokes any available debugging functionality, such as setting a breakpoint. If no debugging functionality is available, this statement has no effect.") 179 | - [`default`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/default "The default keyword can be used in two situations in JavaScript: within a switch statement, or with an export statement.") 180 | - [`delete`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/delete "The JavaScript delete operator removes a property from an object; if no more references to the same property are held, it is eventually released automatically.") 181 | - [`do`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/do...while "The do...while statement creates a loop that executes a specified statement until the test condition evaluates to false. The condition is evaluated after executing the statement, resulting in the specified statement executing at least once.") 182 | - [`else`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else "The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.") 183 | - [`export`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/export "The export statement is used when creating JavaScript modules to export functions, objects, or primitive values from the module so they can be used by other programs with the import statement.") 184 | - [`extends`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/class "The class declaration creates a new class with a given name using prototype-based inheritance.") 185 | - [`finally`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch "The try...catch statement marks a block of statements to try, and specifies a response, should an exception be thrown.") 186 | - [`for`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for "The for statement creates a loop that consists of three optional expressions, enclosed in parentheses and separated by semicolons, followed by a statement (usually a block statement) to be executed in the loop.") 187 | - [`function`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/function "The function declaration defines a function with the specified parameters.") 188 | - [`if`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/if...else "The if statement executes a statement if a specified condition is truthy. If the condition is falsy, another statement can be executed.") 189 | - [`import`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/import) 190 | - [`in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/in "The in operator returns true if the specified property is in the specified object or its prototype chain.") 191 | - [`instanceof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/instanceof "The instanceof operator tests whether the prototype property of a constructor appears anywhere in the prototype chain of an object.") 192 | - [`new`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/new "The new operator creates an instance of a user-defined object type or of one of the built-in object types that has a constructor function.") 193 | - [`return`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/return "The return statement ends function execution and specifies a value to be returned to the function caller.") 194 | - [`super`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/super "The super keyword is used to access and call functions on an object's parent.") 195 | - [`switch`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/switch "The switch statement evaluates an expression, matching the expression's value to a case clause, and executes statements associated with that case, as well as statements in cases that follow the matching case.") 196 | - [`this`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/this "A function's this keyword behaves a little differently in JavaScript compared to other languages. It also has some differences between strict mode and non-strict mode.") 197 | - [`throw`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/throw "The throw statement throws a user-defined exception. Execution of the current function will stop (the statements after throw won't be executed), and control will be passed to the first catch block in the call stack. If no catch block exists among caller functions, the program will terminate.") 198 | - [`try`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/try...catch "The try...catch statement marks a block of statements to try, and specifies a response, should an exception be thrown.") 199 | - [`typeof`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof "The typeof operator returns a string indicating the type of the unevaluated operand.") 200 | - [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var "The var statement declares a variable, optionally initializing it to a value.") 201 | - [`void`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/void "The void operator evaluates the given expression and then returns undefined.") 202 | - [`while`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/while "The while statement creates a loop that executes a specified statement as long as the test condition evaluates to true. The condition is evaluated before executing the statement.") 203 | - [`with`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/with "The with statement extends the scope chain for a statement.") 204 | - [`yield`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/yield "The yield keyword is used to pause and resume a generator function (function* or legacy generator function).") 205 | 206 | # 2. General Guidelines: 207 | 208 | ### This section is for an overview, and will get more in detail in a later section if desired. 209 | 210 | ### A. Avoid Global Variables: 211 | Know the difference between variable declarations. [Read More](https://www.w3schools.com/js/js_best_practices.asp) 212 | 213 | ### B. Declare Functions and Variables at the top of the appropriate scope. 214 | Know the appropriate scope for your variable and type of declaration you should use in JavaScript [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_scope) 215 | 216 | ### C. Never declare Number, String, or Boolean Objects, there are better ways to declare 217 | 218 | ### D. Beware of Automatic Type Conversions 219 | JavaScript is loosely typed [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Dynamic_typing) 220 | 221 | ### E. Comparison Operators ( Use === Comparison) 222 | 223 | 224 | # 225 | ## A. Avoid Global Variables 226 | 227 | When you declare a variable outside of any function, it is called a **`global`** variable, because it is available to any other code in the current document. 228 | When you declare a variable within a function, it is called a 229 | **`local`** variable, because it is available only within that function. With es6 (in React) There is also a *block* scope which I will discuss further in the declaring variables section. 230 | 231 | ### Example of Global Variables 232 | ```js 233 | //Initiate count 234 | var count = 0; 235 | // Function to increment count 236 | function add() { 237 | count += 1; 238 | } 239 | // Call add() 3 times 240 | add(); 241 | add(); 242 | add(); 243 | 244 | // The counter is now 3 245 | ``` 246 | 247 | ### Local Variable Declaration and Functionality 248 | Example: 249 | ```js 250 | const add = (function(){ 251 | let counter = 0; 252 | return ()=>{ 253 | counter += 1; 254 | return counter; 255 | } 256 | })(); 257 | add(); 258 | ``` 259 | - The variable **add** is assigned the return value of a self-invoking function. 260 | 261 | - The self-invoking function only runs once. It sets the counter to zero (0), and returns a function expression. 262 | 263 | - This way add becomes a function. The "wonderful" part is that it can access the counter in the parent scope. 264 | 265 | - This is called a JavaScript **closure.** It makes it possible for a function to have "**private**" variables. 266 | 267 | - The counter is protected by the scope of the anonymous function, and can only be changed using the add function. 268 | 269 | For More On JS Closures: [Read Here](https://www.w3schools.com/js/js_function_closures.asp) 270 | 271 | ### See closures in action: [Finger Guessing Game on Codepen!](https://codepen.io/rforcier2/pen/mZooNq) 272 | 273 | Looking a little more closely at how this can interact with an HTML DOM Element: 274 | - We want to initialize a counter on the page 275 | - We want it to increment by one without using global variables, as then the variable can be accessed outside of its scope. 276 | 277 | ## **A closure is a function having access to the parent scope, even after the parent function has closed** 278 | 279 | ```js 280 | 281 |

0

282 | 283 | 301 | ``` 302 | - [Closures Demo on Codepen](https://codepen.io/rforcier2/pen/pGaBwK) 303 | 304 | ## B. Variable / Functional Declarations at the Top of Scope: 305 | 306 | It is a good coding practice to put all declarations at the top of each script or function. 307 | 308 | This will: 309 | 310 | - Give cleaner code 311 | - Provide a single place to look for local variables 312 | - Make it easier to avoid unwanted (implied) global variables 313 | - Reduce the possibility of unwanted re-declarations 314 | 315 | 316 | Types of Variable Declarations: 317 | 318 | [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) = Declares a variable, optionally initializing it to a value. 319 | 320 | [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) = Declares a block-scoped, local variable, optionally initializing it to a value. 321 | 322 | [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const ) = Declares a block-scoped, read-only named constant. 323 | 324 | **var** vs. **let** 325 | Check out the following example: 326 | 327 | **var** 328 | ```js 329 | if (true) { 330 | var x = 5; 331 | } 332 | console.log("x is " + x); 333 | // x is 5 334 | ``` 335 | **let** 336 | 337 | ```js 338 | if (true) { 339 | let y = 5; 340 | } 341 | console.log("y is " + y); 342 | // ReferenceError: y is not defined 343 | ``` 344 | 345 | *Variable Hoisting*: 346 | All `var` statements in a function should be placed as near to the top of the function as possible. It will be *hoisted* if not declared at the top, meaning JavaScript will move the declaration to the top for you, but this is not best practice and you should not rely on it. 347 | [Read More on Variable Hoisting](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Variable_hoisting) 348 | 349 | ### Function Declaration: 350 | **Always** initialize a function *before* using it. 351 | ```js 352 | // Declare and initiate at the beginning 353 | var firstName = "", 354 | lastName = "", 355 | price = 0, 356 | discount = 0, 357 | fullPrice = 0, 358 | tax = 0, 359 | myArray = [], 360 | myObject = {}; // remember to end declarations with a semi-colon. 361 | 362 | // Declare Functions: 363 | function foo() { 364 | firstName ="Jimmy"; 365 | console.log(firstName); 366 | } 367 | 368 | var baz = function() { 369 | price = 15; 370 | tax = 10; 371 | discount = 5; 372 | fullPrice = (price + tax) - discount; 373 | console.log(fullPrice); 374 | }; 375 | 376 | if (foo(); //result: "Jimmy"; 377 | baz(); //result: "20"; 378 | ``` 379 | 380 | ## C. Never Initialize a Number, String, or Boolean as Objects, there are Better ways to declare Them 381 | 382 | **In these examples, we prefer to declare like x and *NOT* like y.** 383 | ```js 384 | var x = "John"; 385 | var y = new String("John"); 386 | console.log(x === y); 387 | /*console log = false 388 | because x is a string and y is an object.*/ 389 | ``` 390 | or 391 | ```js 392 | var x = new String("John"); 393 | var y = new String("John"); 394 | console.log(x == y) 395 | // console logs false because you cannot compare objects. 396 | ``` 397 | 398 | Keep your declarations like the following: 399 | ```js 400 | var x1 = {}; // new object 401 | var x2 = ""; // new string 402 | var x3 = 0; // new number 403 | var x4 = false; // new boolean 404 | var x5 = []; // new array 405 | var x6 = /()/; // new regexp 406 | var x7 = function(){}; // new function 407 | ``` 408 | 409 | ## D. Beware, Beware the Automatic Type Conversions 410 | 411 | For example, you could define a variable as follows: 412 | ```js 413 | var answer = 42; 414 | ``` 415 | And later, you could assign the same variable a string value, for example: 416 | ```js 417 | answer = 'Thanks for all the fish...'; 418 | ``` 419 | 420 | Because JavaScript is dynamically typed (read: loosely typed), this assignment does not cause an error message. 421 | 422 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Data_structures#Dynamic_typing) 423 | 424 | ## 5. Comparison Operators ( Use === Comparison) 425 | 426 | The == comparison operator always converts (to matching types) before comparison. 427 | 428 | The === operator forces comparison of values and type 429 | 430 | #### (==) examples: 431 | ```js 432 | 1 == 1 // true 433 | '1' == 1 // true 434 | 1 == '1' // true 435 | 0 == false // true 436 | 0 == null // false 437 | var object1 = {'key': 'value'}, object2 = {'key': 'value'}; 438 | object1 == object2 //false 439 | 0 == undefined // false 440 | null == undefined // true 441 | ``` 442 | 443 | #### (===) examples: 444 | ```js 445 | 3 === 3 // true 446 | 3 === '3' // false 447 | var object1 = {'key': 'value'}, object2 = {'key': 'value'}; 448 | object1 === object2 //false 449 | ``` 450 | 451 | 452 | # 3. ES6 Specific Syntax & Modularization of React Components 453 | 454 | ## ES6 Useful Features for React-Native functionality 455 | These are the ES6 features that I believe to be most important / relevant to this project: 456 | Note: Some will look slightly different constructed using React's Components, but this will give you the initial idea 457 | 458 | - [Arrows](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) 459 | - [Classes](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) 460 | - [let + const](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations) 461 | - [Iterators + for..of](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) 462 | - [Promises](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) 463 | ### If you're too lazy to check the MDN docs here are some quick examples for you: 464 | 465 | ### Arrow Function Example: 466 | ```js 467 | var materials = [ 468 | 'Hydrogen', 469 | 'Helium', 470 | 'Lithium', 471 | 'Beryllium' 472 | ]; 473 | //this function returns the length of each material 474 | console.log(materials.map(element => element.length)); 475 | // expected output: Array [8, 6, 7, 9] 476 | ``` 477 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Functions/Arrow_functions) 478 | # 479 | 480 | ### Class Declaration Example: 481 | ```js 482 | class Rectangle { 483 | constructor(height, width) { 484 | this.height = height; 485 | this.width = width; 486 | } 487 | 488 | position(x, y) { 489 | this.x = x; 490 | this.y = y; 491 | } 492 | } 493 | ``` 494 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Classes) 495 | 496 | ### Classes (more in depth) Examples: 497 | 498 | ```js 499 | class Rectangle { 500 | constructor(width, height){ 501 | this.width = width; 502 | this.height = height; 503 | } 504 | 505 | get area() { 506 | return this.calcArea(); 507 | } 508 | 509 | calcArea() { 510 | return this.height * this.width; 511 | } 512 | 513 | get perimeter(){ 514 | return this.calcPerimeter(); 515 | } 516 | } 517 | 518 | Rectangle.prototype.calcPerimeter = function(){ 519 | return (this.height*2)+(this.width*2); 520 | } 521 | 522 | Object.defineProperty(Rectangle, 'diagonal', {get: function(){ 523 | return Math.sqrt(Math.pow(this.height, 2), Math.pow(this.width*2))} 524 | }); 525 | 526 | const mySquare = new Rectangle(20, 20); 527 | console.log( mySquare.area ); // 200 528 | console.log( mySquare.calcArea() ); // 200 529 | console.log( mySquare.perimeter ); // 80 530 | console.log( +(mySquare.diagonal.toFixed(2)) ); // 28.28 531 | // this formula is typically used for rectangles, but wil also work for 532 | // squares (square formula is: diagonal = side*sqrt(2) ( or 28.28) ) 533 | 534 | // Also used + (unary operator, can also use Number()) to ensure we get an accurate number rather than 535 | // parseInt() method which... you guessed it, makes the number a round integer. 536 | // Fun fact: This method operates similarly to Math.floor() and will give you the nearest whole 537 | // integer less than the current value. (in this example we get 28, antoher: parseInt(2.9999) = 2. 538 | ``` 539 | 540 | To declare a new instance of an object we must use the _new_ keyword. 541 | For the example here we declared the variable 'mySquare' as a 'new Rectangle'; 542 | 543 | The get the area we can use a get method. This creates a psuedo-property 'area' that, in this case, returns the result of another function. 544 | 545 | As you see in the last example "Object.define property" defines a new get method for our class. 546 | 547 | ## This keyword 548 | __this__ keyword is used to reference the current object. Every method / object has their own "this" keyword in reference to itself. We are declaring a constructor, which we will use to "contruct" our new object. If this was a person, maybe we would give them a constructor with a name and an age. But for this example, width and height do just fine. 549 | You can reference the "this" keyword anywhere within the class, and through external prototype methods and the definition of get methods. 550 | 551 | ## Declaring Methods 552 | in the class we declare mathods as 553 | ```js 554 | class Example{ 555 | constructor(){} 556 | methodName(){ 557 | // code for this method here 558 | return this; 559 | } 560 | } 561 | ``` 562 | Every class needs a constructor method, whether or not you need it. 563 | 564 | ## Prototype Methods 565 | 566 | If the method may be called many times, and you are in a massive workspace, with hundreds or even thousands of methods, you should get used to using prototype. 567 | These methods have access to all of the Object properties, but are not initiated with the object itself. Not only can you use prototype methods on objects YOU have declared, but also on built in Javascript objects. Since we have already seen a prototype method regarding an object we declared let's see one using the String object: 568 | 569 | ```js 570 | String.prototype.index0length = function(){ 571 | return this.length-1; 572 | } 573 | 574 | var myStr = "people love me"; 575 | console.log(myStr.length) //14 576 | console.log(myStr.index0length()); //13 577 | ``` 578 | Isn't that neat! Go forth and blossom and make those objects wish they had been initiated sooner! 579 | 580 | 581 | # 582 | 583 | ### Let + Const: 584 | Technically already reviewed, but 585 | 586 | [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) 587 | Declares a variable, optionally initializing it to a value. 588 | 589 | [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) 590 | Declares a block-scoped, local variable, optionally initializing it to a value. 591 | 592 | [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const) 593 | Declares a block-scoped, read-only named constant. 594 | 595 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Grammar_and_types#Declarations) 596 | 597 | # 598 | 599 | ### Iterators: 600 | 601 | ### Difference between `for...of` and `for...in` 602 | 603 | Both `for...in` and `for...of` statements iterate over something. The main difference between them is in what they iterate over. 604 | 605 | The [`for...in`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...in) statement iterates over the [enumerable properties](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Enumerability_and_ownership_of_properties) of an object, in an arbitrary order. 606 | 607 | The `for...of` statement iterates over data that [iterable object](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Iterators_and_Generators#Iterables) defines to be iterated over. 608 | 609 | **Iterating over an array:** 610 | ```js 611 | let iterable = [10, 20, 30]; 612 | 613 | for (let i of iterable) { 614 | i++; 615 | console.log(i); 616 | } 617 | // 11 618 | // 21 619 | // 31 620 | 621 | for (let i in iterable){ 622 | i++; 623 | console.log(i); 624 | } 625 | // 1 626 | // 2 627 | // 3 628 | ``` 629 | 630 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/for...of) 631 | 632 | 633 | 634 | ## Promises: 635 | (I decided to give promises more room because they *rock*) 636 | 637 | Unlike old-style passed-in callbacks, a promise comes with some guarantees: 638 | 639 | - Callbacks will never be called before the [completion of the current run](https://developer.mozilla.org/en-US/docs/Web/JavaScript/EventLoop#Run-to-completion) of the JavaScript event loop. 640 | - Callbacks added with [then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) even _after_ the success or failure of the asynchronous operation, will be called, as above. 641 | - Multiple callbacks may be added by calling [then()](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Promise/then) several times. Each callback is executed one after another, in the order in which they were inserted. 642 | 643 | One of the great things about using promises is **chaining**. 644 | ### Chaining: 645 | ```js 646 | const Promise = doSomething(); 647 | const Promise_2 = promise.then(successCallback, failureCallback); 648 | ``` 649 | In the old days, doing several asynchronous operations in a row would lead to the classic callback "hell": 650 | 651 | ```js 652 | doSomething(function(result) { 653 | doSomethingElse(result, function(newResult) { 654 | doThirdThing(newResult, function(finalResult) { 655 | console.log('Got the final result: ' + finalResult); 656 | }, failureCallback); 657 | }, failureCallback); 658 | }, failureCallback); 659 | ``` 660 | 661 | With promises and arrow functions, promises now look like this: 662 | ```js 663 | doSomething() 664 | .then(result => doSomethingElse(result)) 665 | .then(newResult => doThirdThing(newResult)) 666 | .then(finalResult => { 667 | console.log(`Got the final result: ${finalResult}`); 668 | }) 669 | .catch(failureCallback); 670 | ``` 671 | [Read More](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Using_promises) 672 | 673 | If you would like some real examples of promises visit my codepen! 674 | - [Get the Weather](https://codepen.io/rforcier2/pen/PrLjEO) 675 | - [Get your Github](https://codepen.io/rforcier2/pen/LKdmNy) 676 | 677 | ## Modularizing the React Workspace 678 | Sources: 679 | 680 | [How to Better Organize React Apps](https://medium.com/@alexmngn/how-to-better-organize-your-react-applications-2fd3ea1920f1) 681 | 682 | [Why React Devs should Modularize](https://medium.com/@alexmngn/why-react-developers-should-modularize-their-applications-d26d381854c1) 683 | 684 | [JavaScript Module Pattern in depth](http://www.adequatelygood.com/JavaScript-Module-Pattern-In-Depth.html) 685 | 686 | ![Universal Components for a Modular App](https://i.imgur.com/2NLmj0W.png) 687 | 688 | 689 | First, I want to provide an ideal / modular file base architecture: 690 | ```js 691 | /src 692 | /components 693 | /Button 694 | /Notifications 695 | /components 696 | /ButtonDismiss 697 | /images 698 | /locales 699 | /specs 700 | /index.js 701 | /styles.scss 702 | /index.js 703 | /styles.scss 704 | 705 | /scenes 706 | /Home 707 | /components 708 | /ButtonLike 709 | /services 710 | /processData 711 | /index.js 712 | /styles.scss 713 | 714 | /Sign 715 | /components 716 | /FormField 717 | /scenes 718 | /Login 719 | /Register 720 | /locales 721 | /specs 722 | /index.js 723 | /styles.scss 724 | 725 | /services 726 | /api 727 | /geolocation 728 | /session 729 | /actions.js 730 | /index.js 731 | /reducer.js 732 | /users 733 | /actions.js 734 | /api.js 735 | /reducer.js 736 | 737 | index.js 738 | store.js 739 | ``` 740 | In this example, you can see how each module is grouped with similar components. Part of Modular Design: 741 | > each component, scene or service (a feature) has everything it needs to work on its own, such as its own styles, images, translations, set of actions as well as unit or integration tests. 742 | 743 | Grouping Components based on utilization will be huge. Keeping folders, components, and modules separate and with like-content is very important. 744 | 745 | 746 | # 4 Summary: 747 | 748 | ## Declarations: 749 | ### Variable Declarations: 750 | 751 | [`var`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/var) = Declares a variable, optionally initializing it to a value. 752 | 753 | [`let`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/let) = Declares a block-scoped, local variable, optionally initializing it to a value. 754 | 755 | [`const`](https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Statements/const ) = Declares a block-scoped, read-only named constant. 756 | 757 | ### Declaring Objects in JavaScript 758 | ```js 759 | var x1 = {}; // new object 760 | var x2 = ""; // new string 761 | var x3 = 0; // new number 762 | var x4 = false; // new boolean 763 | var x5 = []; // new array 764 | var x6 = /()/; // new regexp 765 | var x7 = function(){}; // new function 766 | ``` 767 | ### Declaring a Function: 768 | You can name a function 769 | ```js 770 | function foo() { 771 | firstName = "Rexxar"; 772 | console.log(firstName); 773 | } 774 | 775 | var baz = function() { 776 | console.log("Me Go Face, Taunt is Cheat"); 777 | } 778 | 779 | foo(); 780 | baz(); 781 | ``` 782 | 783 | **Iterating over an array:** 784 | ```js 785 | let iterable = [10, 20, 30]; 786 | 787 | for (let i of iterable) { 788 | i++; 789 | console.log(i); 790 | } 791 | // 11 792 | // 21 793 | // 31 794 | 795 | for (let i in iterable){ 796 | i++; 797 | console.log(i); 798 | } 799 | // 1 800 | // 2 801 | // 3 802 | ``` 803 | 804 | ## React Specific: 805 | 806 | The main piece of advice you will always hear when practicing React is to NEVER set the state directly. 807 | There is a method in React that allows you to do that called ```setState()``` 808 | 809 | ### React / Redux short read on importance: 810 | [Source](https://pub.monospacelabs.com/react-native-developing-using-best-practices-part-1-9d6f3bd77a68) 811 | 812 | #### What’s Redux? 813 | As its documentation states, redux is a predictable state container for JavaScript applications. It’s both regular library and a data-flow architecture. A lot of people think that it comes with React Native and it is just another tool of it. That’s a big misunderstanding! It’s a framework-agnostic tool that fits with React Native really well but it still can be used with almost any JavaScript library or framework like jQuery, Angular, Ember, Meteor or even vanilla JavaScript. 814 | 815 | #### Why should I use it? 816 | React does not consider direct component-to-component communication as a good practice even if it has the ability to support it. An architecture like this, is going to lead to a poorly structured source code sooner or later which will be difficult to maintain and scale. Redux offers a way to store all of the application state in just one place with global scope. Then your React Native components dispatch actions that trigger changes to the store. Components that need to “know” about those changes should be connected to Redux state. 817 | 818 | #### You may hear about Flux, but what is it? And how does it compare to my precious Redux? 819 | 820 | Redux is not _that_ different from Flux. Overall it has same architecture, but Redux is able to cut some complexity corners by using functional composition where Flux uses callback registration. 821 | 822 | There is not a fundamental difference in Redux, but I find it makes certain abstractions easier, or at least possible to implement, that would be hard or impossible to implement in Flux. 823 | 824 | [Read More on Stack Overflow](https://stackoverflow.com/questions/32461229/why-use-redux-over-facebook-flux) 825 | 826 | 827 | # Bonus Section 828 | If you made it this far, perhaps you like to read, or are maybe desperate. Anywho, here is compilation of common mistakes in JavaScript, an explanation of what went wrong, and how to fix it. 829 | 830 | ### [Read More](https://www.w3schools.com/js/js_mistakes.asp) 831 | 832 | ## First Lesson: Assignment Operator Mishap 833 | 834 | This if statement returns true (hopefully not as expected), because 10 is true: 835 | ```js 836 | var x = 0; // initializing x to 0 837 | if (x = 10) // setting it's value to 10, 838 | // not comparing! 839 | ``` 840 | 841 | This *if* statement returns false (as expected) because x is not equal to 10: 842 | ```js 843 | var x = 0; // initializing x to 0 844 | if (x == 10) // Comparing it's value to 10 845 | // or if (x === 10) 846 | // This (===) would check type AND value. 847 | ``` 848 | 849 | ## Using Strict Mode 850 | `StrictMode` currently helps with: 851 | 852 | - [Identifying components with unsafe lifecycles](https://reactjs.org/docs/strict-mode.html#identifying-unsafe-lifecycles) 853 | - [Warning about legacy string ref API usage](https://reactjs.org/docs/strict-mode.html#warning-about-legacy-string-ref-api-usage) 854 | - [Detecting unexpected side effects](https://reactjs.org/docs/strict-mode.html#detecting-unexpected-side-effects) 855 | - [Detecting legacy context API](https://reactjs.org/docs/strict-mode.html#detecting-legacy-context-api) 856 | 857 | ### Example: 858 | ```js 859 | import React from 'react'; 860 | 861 | function ExampleApplication() { 862 | return ( 863 | 864 |
865 | 866 | 867 | 868 | 869 | 870 | 871 |