Day 39 - 18/10
Plan:
Learning Js: JSON, Debugging, Style guide, Best practices, Mistakes, Performance, Reserved words, Js ES6, ...
Progress:
JSON - JavaScript Object Notation
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
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>
Coding conventions
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
Best practice
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
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.
Common Mistakes
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;
x = 10 + 5; // Now x is 15
let y = 10;
y += "5"; // Now y is "105"
Misunderstanding Floats
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
Breaking a JavaScript String
Allowed:
let x =
"Hello World!";
Not allowed:
let x = "Hello
World!";
Allowed:
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 isundefined.
Instead, test if an object is notundefined,
and notnull
if (typeof myObj !== "undefined" && myObj !== null)
Performance
Reduce activity in loops
Place statements and assignments outside the loop will make the loop run faster.
let l = arr.length;
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 .
Js ES6
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 thanvar
because a function expression is always a constant valuecan 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];
let maxValue = Math.max(...numbers);
The for/of loop
Loop through the values of an iterable object
const cars = ["BMW", "Volvo", "Mini"];
let text = "";
for (let x of cars) { text += x + " "; }
Maps
Able to use an Object as a key
const fruits = new Map([
["apples", 500],
["bananas", 300],
["oranges", 200] ]);
Sets
Classes
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);
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
function myFunction(x, y = 10) {
// y is 10 if not passed or undefined
return x + y; }
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) {
let sum = 0;
for (let arg of args) sum += arg;
return sum; }
let x = sum(4, 9, 16, 25, 29, 100, 66, 77);
String
.includes() : The
includes()
method returnstrue
if a string contains a specified value, otherwisefalse
.startsWith() : returns
true
if a string begins with a specified value, otherwisefalse
.endsWith() : returns
true
if a string ends with a specified value, otherwisefalse
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
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() :
returnstrue
if the argument is an integerNumber.isSafeInteger()
: returnstrue
if the argument is a safe integer.
New global method
isFinite() :
returnsfalse
if the argument is Infinity or NaNisNaN() :
returnstrue
if the argument isNaN
Object entries() method
entries()
returns an Array Iterator object with key/value pairs and doesnt change the original array.
Modules
Last updated