Day 39 - 18/10
Last updated
Last updated
Plan:
Learning Js: JSON, Debugging, Style guide, Best practices, Mistakes, Performance, Reserved words, Js ES6, ...
Converting figma to html:
Progress:
What:
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
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>
names written as camelCase
global var written in UPPERCASE
constants written in UPPERCASE
hyphens ( - ) are not allowed
dont start with $ sign
Always put spaces around operators and after commas
Always use 2 spaces for indentation of code blocks
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
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 < 80
Use simple syntax for loading external scripts
<script src="myscript.js"></script>
Global variables and functions can be overwritten by other scripts.
Use local variables instead, and learn how to use closures.
Prevent any accidental change of type
Prevent any accidental change of type
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(){};
A variable can contain all data types.
A variable can change its data type:
let x = "Hello"; // typeof x is a string
x = 5; // changes typeof x to a number
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
Always end your switch
statements with a default
Always treat numbers, strings, or booleans as primitive values. Not as objects.
accidentally use ( = ) instead of ( == )
In regular comparison, data type does not matter; but in strict comparison, it does matter
Case switch use strict comparison
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;
x = 10 + 5; // Now x is 15
let y = 10;
y += "5"; // Now y is "105"
All programming languages, including JavaScript, have difficulties with precise floating point values
let x = 0.1;
let y = 0.2;
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
Allowed:
let x =
"Hello World!";
Not allowed:
let x = "Hello
World!";
Allowed:
let x = "Hello \
World!";
a statement is automatically closed at the end of a line
allow to break a statement into two lines except for return
Js doesnt support array with named index, just numbered index
const person = [];
person[0] = "John"; //allowed
person["firstName"] = "John"; //not allowed
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)
Place statements and assignments outside the loop will make the loop run faster.
let l = arr.length;
for (let i = 0; i < l; i++) {}
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
Replace
let fullName = firstName + " " + lastName; document.getElementById("demo").innerHTML = fullName;
with
document.getElementById("demo").innerHTML = firstName + " " + lastName;
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 .
let
declares var with block scope
const declares a constant with block scope and unchangeable value
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 };
When ...arr is used, it ‘expands’ an iterable object arr into the list of arguments.
const numbers = [23,55,21,87,56];
let maxValue = Math.max(...numbers);
Loop through the values of an iterable object
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) { text += x + " "; }
Able to use an Object as a key
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200] ]);
JavaScript Classes are templates for JavaScript Objects, not an object
class Car {
constructor(name, year) {
this.name = name;
this.year = year; }
}
Can use the class to create objects
const myCar1 = new Car("Ford", 2014);
An object that links "Producing Code" and "Consuming Code"
"Producing Code" can take some time and "Consuming Code" must wait for the result
ES6 allows function parameters to have default values
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y; }
myFunction(5); // will return 15
The rest parameter (...) allows a function to treat an indefinite number of arguments as an array:
function sum(...args) {
let sum = 0;
for (let arg of args) sum += arg;
return sum; }
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
.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
.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.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
Math.log2(x) : returns the log base 2 logarithm of x
Math.log10(x) : returns the log base 10 logarithm of x
Number.EPSILON; //2.220446049250313e-16
Number.MIN_SAFE_INTEGER; //-9007199254740991
Number.MAX_SAFE_INTEGER; //9007199254740991
Number.isInteger() :
returns true
if the argument is an integer
Number.isSafeInteger()
: returns true
if the argument is a safe integer.
isFinite() :
returns false
if the argument is Infinity or NaN
isNaN() :
returns true
if the argument is NaN
entries()
returns an Array Iterator object with key/value pairs and doesnt change the original array.