# Day 39 - 18/10

Plan:&#x20;

* Learning Js: JSON, Debugging, Style guide, Best practices, Mistakes, Performance, Reserved words, Js ES6, ...
* Converting figma to html: <https://www.figma.com/file/xciG3uwGq4GWWHy3DuFlnM/About-us?type=design&node-id=0%3A1&mode=design&t=0Pz86OGygx2PqiXA-1>

Progress:&#x20;

## <mark style="color:blue;">JSON - JavaScript Object Notation</mark>

What:&#x20;

* a lightweight data interchange format
* language independent (JSON format is text only; code for reading and generating JSON data can be written in any programming language)
* "self-describing" and easy to understand

The JSON format is syntactically identical to the code for creating JavaScript objects.

Syntax rules:

* data is in name/value pair
* data is separated by commas
* curly braces hold objects
* square brackets hold arrays

Common use of JSON is to read data from web server and display it in a web page

#### Convert a JSON text to a Js Object

* Create a Js string containing JSON syntax

`let text = '{ ... JSON ... }';`

* Use `JSON.parse()` to convert the string into a JavaScript object

`const obj = JSON.parse(text);`

* Use the new JavaScript object in your page with the new name

`<p id="demo"></p>`

`<script>`

`document.getElementById("demo").innerHTML = obj.employees[1].firstName + " " + obj.employees[1].lastName;`

`</script>`

## <mark style="color:blue;">Coding conventions</mark>

### Naming

* names written as camelCase
* global var written in UPPERCASE
* constants written in UPPERCASE
* hyphens ( - ) are not allowed
* dont start with $ sign

### Operators

Always put spaces around operators and after commas

### Code indentation

Always use 2 spaces for indentation of code blocks

### Statement rules

* Always end a simple statement with a semicolon
* Put the opening bracket at the end of the first line
* Use one space before the opening bracket
* Put the closing bracket on a new line, without leading spaces
* Do not end a complex statement with a semicolon

### Object rules

* Place the opening bracket on the same line as the object name
* Use colon plus one space between each property and its value
* Use quotes around string values, not around numeric values
* Do not add a comma after the last property-value pair
* Place the closing bracket on a new line, without leading spaces
* Always end an object definition with a semicolon

### Line length

Line length < 80

### Loading JavaScript in HTML

Use simple syntax for loading external scripts

`<script src="myscript.js"></script>`

### Use lowercase file name

## <mark style="color:blue;">Best practice</mark>

### Avoid global variable

Global variables and functions can be overwritten by other scripts.

Use local variables instead, and learn how to use closures.

### Always declare local variable

### Declarations on top

### Declare object with const

Prevent any accidental change of type

### Declare array with const

Prevent any accidental change of type

### Don't Use new Object()

* Use "" instead of new String()

`let x1 = "";`

* Use 0 instead of new Number()

`let x2 = 0;`

* Use false instead of new Boolean()

`let x3 = false;`

* Use {} instead of new Object()

`const x4 = {};`

* Use \[] instead of new Array()

`const x5 = [];`

* Use /()/ instead of new RegExp()

`const x6 = /()/;`

* Use function (){} instead of new Function()

`const x7 = function(){};`

### Beware of Automatic Type Conversions

A variable can contain all data types.

A variable can change its data type:

`let x = "Hello"; // typeof x is a string`&#x20;

`x = 5; // changes typeof x to a number`

### Use Parameter Defaults

If a function is called with a missing argument, the value of the missing argument is set to `undefined`.

It is a good habit to assign default values to arguments

### End Switches with Defaults

Always end your `switch` statements with a `default`

### Avoid Number, String, and Boolean as Objects

Always treat numbers, strings, or booleans as primitive values. Not as objects.

## <mark style="color:blue;">Common Mistakes</mark>

### Accidentally Using the Assignment Operator

accidentally use ( = ) instead of ( == )

### Loose Comparison

In regular comparison, data type does not matter; but in strict comparison, it does matter

Case switch use strict comparison

### Confusing Addition (add numbers) & Concatenation (add strings)

Both uses the same ( + ) operator but adding a number as a number will produce a different result from adding a number as a string

`let x = 10;`&#x20;

`x = 10 + 5; // Now x is 15`

`let y = 10;`&#x20;

`y += "5"; // Now y is "105"`

### Misunderstanding Floats

All programming languages, including JavaScript, have difficulties with precise floating point values

`let x = 0.1;`&#x20;

`let y = 0.2;`&#x20;

`let z = x + y // the result in z will not be 0.3`

to solve

`let z = (x * 10 + y * 10) / 10; // z will be 0.3`

### Breaking a JavaScript String

Allowed:   &#x20;

`let x =`&#x20;

`"Hello World!";`

Not allowed:

`let x = "Hello`&#x20;

`World!";`

Allowed:&#x20;

`let x = "Hello \`

`World!";`

### Misplacing Semicolon

### Breaking a Return Statement

* a statement is automatically closed at the end of a line
* allow to break a statement into two lines except for `return`

### Access array with named index

Js doesnt support array with named index, just numbered index

`const person = [];`

`person[0] = "John";           //allowed`

`person["firstName"] = "John"; //not allowed`

### Undefined != Null

* Can test if an object exists by testing if the type is `undefined`
* cannot test if an object is `null`, because this will throw an error if the object is `undefined.` Instead, test if an object is not `undefined,` and  not `null`

`if (typeof myObj !== "undefined" && myObj !== null)`

## <mark style="color:blue;">Performance</mark>

### Reduce activity in loops

Place statements and assignments outside the loop will make the loop run faster.

`let l = arr.length;`&#x20;

`for (let i = 0; i < l; i++) {}`

### Reduce DOM access

Accessing the HTML DOM is very slow, if expect to access a DOM element several times, access it once, and use it as a local variable

`const obj = document.getElementById("demo"); obj.innerHTML = "Hello";`

Keep the number of elements in the HTML DOM small

### Avoid Unnecessary Variables

Replace

`let fullName = firstName + " " + lastName; document.getElementById("demo").innerHTML = fullName;`

with

`document.getElementById("demo").innerHTML = firstName + " " + lastName;`

### Delay JavaScript Loading

Putting scripts at the bottom, before the body close tag lets the browser load the page first, reduce the page loading time because Js file might be large .

## <mark style="color:blue;">Js ES6</mark>

### Let

`let` declares var with block scope

### Const

const declares a constant with block scope and unchangeable value

### Arrow function

Don't need the `function` keyword, the `return` keyword, and the curly brackets in arrow function

`const x = (x, y) => x * y;`

* not suitable for defining object method
* dont have its own `this`
* not hoisted
* use `const` is safer than `var`because a function expression is always a constant value
* can only omit the `return` keyword and the curly brackets if the function is a single statement, so just keep them

`const x = (x, y) => { return x * y };`

### Spread (...) operator

* When ...arr is used, it ‘expands’ an iterable object arr into the list of arguments.

`const numbers = [23,55,21,87,56];`&#x20;

`let maxValue = Math.max(...numbers);`

### The for/of loop

* Loop through the values of an iterable object

`const cars = ["BMW", "Volvo", "Mini"];`&#x20;

`let text = "";`

`for (let x of cars) { text += x + " "; }`

### Maps

* Able to use an Object as a key

`const fruits = new Map([`&#x20;

`["apples", 500],`&#x20;

`["bananas", 300],`&#x20;

`["oranges", 200] ]);`

### Sets

### Classes

* JavaScript Classes are templates for JavaScript Objects, not an object

`class Car {`&#x20;

`constructor(name, year) {`&#x20;

`this.name = name;`&#x20;

`this.year = year; }`&#x20;

`}`

* Can use the class to create objects

`const myCar1 = new Car("Ford", 2014);`

### Promises

An object that links "Producing Code" and "Consuming Code"

"Producing Code" can take some time and "Consuming Code" must wait for the result

### Default parameter values

ES6 allows function parameters to have default values&#x20;

`function myFunction(x, y = 10) {`&#x20;

`// y is 10 if not passed or undefined`&#x20;

`return x + y; }`&#x20;

`myFunction(5); // will return 15`

### Function Rest parameter

The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:

`function sum(...args) {`&#x20;

`let sum = 0;`&#x20;

`for (let arg of args) sum += arg;`&#x20;

`return sum; }`

`let x = sum(4, 9, 16, 25, 29, 100, 66, 77);`

### String

* .includes() : The `includes()` method returns `true` if a string contains a specified value, otherwise `false`
* .startsWith() : returns `true` if a string begins with a specified value, otherwise `false`
* .endsWith() : returns `true` if a string ends with a specified value, otherwise `false`

### Array

* .from() : returns an Array object from any object with a length property or any iterable object

`Array.from("ABCDEFG")   // Returns [A,B,C,D,E,F,G]`

* .keys() : returns an Array Iterator object with the keys of an array
* .find() : returns the value of the first array element that passes a test function
* .findIndex() : returns the index of the first array element that passes a test function

### Math method

* Math.trunc(x) : returns the integer part of x
* Math.sign(x) : returns if x is negative, null or positive
* Math.cbrt(x) : returns the cube root of x&#x20;
* Math.log2(x) : returns the log base 2 logarithm of x
* Math.log10(x) : returns the log base 10 logarithm of x

### New number properties

* `Number.EPSILON;     //2.220446049250313e-16`
* `Number.MIN_SAFE_INTEGER;    //-9007199254740991`
* `Number.MAX_SAFE_INTEGER;     //9007199254740991`

### New number method

* `Number.isInteger() :` returns `true` if the argument is an integer
* `Number.isSafeInteger()` :  returns `true` if the argument is a safe integer.

### New global method

* `isFinite() :` returns `false` if the argument is Infinity or NaN
* `isNaN() :` returns `true` if the argument is `NaN`

### Object entries() method

`entries()` returns an Array Iterator object with key/value pairs and doesnt change the original array.

### Modules


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://dtian.gitbook.io/daily-report-1/day-39-18-10.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
