advanced_js

This is the advanced in Javascript as a tags, summarized from Speaking Javascript Book.

 

####################### Syntax #################

The normal (nonstrict) mode is sometimes called “sloppy mode.”
Variables Must Be Declared in Strict Mode.
in strict mode code, functions can only be declared at top level or immediately within another function.
Due to strict mode, you get a warning when you accidentally forget new and call it as a function.
The arguments object is simpler in strict mode.
Illegal manipulations of properties throw exceptions in strict mode.
In strict mode, the eval() function becomes less quirky.
No more octal numbers in strict mode.
Static Versus Dynamic:: static usually means “at compile time” while dynamic means “at runtime.”.
JavaScript is dynamically typed; types of variables are generally not known at compile time.
JavaScript’s built-in conversion (types) mechanisms support only the types Boolean, Number, String, and Object.
all primitive values encoding the same value are considered the same.
Properties can’t be changed, added, or removed.
You can’t define your own primitive types.
Identities are compared; every object has its own identity, EX: ({} === {})// false.
Object properties is Mutable by default, freely change, add, and remove.
nonvalue:: undefined or null.
Uninitialized variables are undefined.
Missing parameters are undefined.
If you read a nonexistent property, you get undefined.
functions implicitly return undefined if nothing has been explicitly returned EX:: function f() {} & function g() { return; }.
checking undefined & null, if (x === null) and if (x === undefined) and you can check for undefined via the typeof.
undefined and null are considered false.
false, 0, NaN, and ” are also considered false.
null becomes 0 if coerced to a number, EX: Number(null)//0, 5 + null//5.
undefined becomes NaN, EX: Number(undefined)// NaN, 5 + undefined// NaN.
undefined is read-only.
Wrapper Objects Are Different from Primitives.
Wrapper instances are objects, and there is no way of comparing objects.
Unwrap a primitive by invoking the method valueOf(), EX: new Number(123).valueOf().
Converting wrapper objects to primitives properly extracts numbers and strings, but not booleans, EX: Boolean(new Boolean(false))// true, String(new String(‘abc’))// ‘abc’.
Most operators only work with primitive values.
Equality Operators:: Strict equality (===) & Normal,lenient equality (==), recommedned to use Always strict equality and avoid lenient equality.
undefined and null, then they are considered leniently equal, Ex: undefined == null.
wrapped primitives, EX:: new String(‘abc’).
The comma operator evaluates both operands and returns the result of right, EX: 123, ‘abc’//’abc’.
void 0 as a synonym for undefined.
many browsers replace the current document with the result of evaluating the URL’s “content,” but only if the result isn’t undefined (void 0).
a default for a parameter, Ex:: text = text || ”;.
Manually Converting to Number, Number(value) or +value.
Special Number Values:: Two error values, NaN and Infinity, And Two values for zero, +0 and -0.
Strange thing, typeof NaN// ‘number’
NaN is the only value that is not equal to itself, EX: NaN === NaN// false.
global function to check whether a value is NaN => isNaN().
Infinity()error value, number can’t be represented because its magnitude is too large, or a division by zero has happened.
Infinity(e1024), EX: Math.pow(2, 1023)// 8.98846567431158e+307 while Math.pow(2, 1024)// Infinity
the global function isFinite() allows you to check if Infinity number.
JavaScript can only safely represent integers i in the range −253 < i < 253, checking by Number.isSafeInteger(i)
all numbers are floating point
Converting to Integer, The Math functions (floor, ceil & round) is the (best) or parseInt() (parsing strings, but not for converting numbers to integers).
Math.floor()// closest lower integer EX: 3.8//3
Math.ceil()// closest higher integer EX: 2.1//3
Math.round()// closest integer Ex:: 3.2//3, 3.5//4, 3.8//4
ToInteger removes the fraction of a floating-point number Ex: 3.2//3, 3.8//3
Don’t use parseInt() to convert a number to an integer.
THE REMAINDER OPERATOR (%) IS NOT MODULO, to use it as modulo you must use Math.abs()

################### Strings ###############

In string you are free to use either kind of quote.
Escaped characters :: All characters except b f n r t v x u and decimal digits represent themselves
Hexadecimal escape sequences, specifies a character via an ASCII code:: \xHH (HH are two hexadecimal digits) EX: ‘\x4D’//’M’
Unicode escape sequences, specifies a UTF-16 code unit:: Ex: \u004D’ // ‘M’
Character Access:: Ex: ‘abc’.charAt(1)// ‘b’, ‘abc'[1]// ‘b’
Manually Converting to String, by:: String(value) as a function and recommedned, ”+value & value.toString()
Objects to string using JSON.stringify(Obj).
Comparing Strings, by:: comparison operators: <, >, ===, <=, >= Or String.prototype.localeCompare(other)
Concatenation: Joining an Array of String Fragments by :: arr.join(”)
String.fromCharCode():: produces a string whose characters are the UTF-16 code
array of numbers into a string:: String.fromCharCode.apply() Ex: String.fromCharCode.apply(null, [97, 98, 99]) // ‘abc’
String methods:: charAt(pos), charCodeAt(pos)//UTF-16 code, slice(start, end?), substring(start, end?), split(separator?, limit?)//return array.
String transform:: str.trim(), concat(str1?, str2?, …), toLowerCase(), toUpperCase().
Search and Compare:: indexOf(searchString, position?), lastIndexOf(searchString, position?), localeCompare(other)???, search(regexp)//index, match(regexp)//match object, replace(search, replacement)

################## Statemenets #############

loop:: for, for-in //objects, forEach()//array & objects.

################ Functions ############

The Three Roles of Functions in JavaScript: normal function, Constructor & Method
“Parameter” Versus “Argument”:: Parameter// define a function, Ex: function foo(param1, param2), Argument// invoke a function, Ex: foo(3, 7)
Function Declarations:: normal and function expression(declares a new variable, creates a function object, and assigns it to the variable) and you can Named function expressions but its must to refer to itself and useful for debugging.
Function declarations are hoisted completely, variable declarations only partially.
var declarations are hoisted, too, but only the declarations
function expression :: results in an error

############## Variables ############

JavaScript hoists all variable declarations, it moves them to the beginning of their direct scopes.
console.log(bar); :: the declaration has been hoisted, but not the assignment.
If you declare a variable that has already been declared, nothing happens.
Avoid Creating Global Variables as much as you can, and u can use scope var by iffe.
Module Systems Lead to Fewer Globals.
environment:: is storage space and it maps variable names to values.

############## Arrays ############

Arrays Are Maps(dictionaries), Not Tuples.
Arrays are still objects and can have object properties.
The in Operator and Indices:: detects whether an object has a property with a given key or determine whether a given element index exists in an array.
the delete operator also deletes array elementsa and the length property is not updated.
To remove elements without creating holes use splice().
length does not count the number of elements its track the highest index in an array.
you can manually Increasing/Decreasing the Length of an Array.
An array with holes is called sparse. An array without holes is called dense.
Iteration via forEach skips the holes.
map() skips, but preserves holes.
Removing Holes from Arrays by filter().
Array Prototype Methods: shift(), unshift(), pop(), push(), splice(), reverse(), sort(), concat()//not affect the original, slice(), join()//toString
the sorting compares values by converting them to strings, which means that numbers are not sorted numerically.
Searching for Values:: indexOf(searchValue), every(callback)//every element, some(callback)//at least one element, map(callback)//produce an output array depend on callback controls, filter(callback).
Reduction Methods:: reduce()

############ Objects and Inheritance ###########

layers:: single objects, Prototype chains of objects, Constructors as factories for instances(classes) & Inheritance Between Constructors.
single obj, defineProperty() and configure it to be deleted or not.
dot operator works with fixed property keys, the bracket operator allows you to refer to a property via an expression.
functions are also objects.
Bind creates a new function that will have this set to the first parameter passed to bind().
The prototype relationship between two objects is about inheritance: every object can have another object as its prototype. Then the former object inherits all of its prototype’s properties. An object specifies its prototype via the internal property [[Prototype]] or __proto__. Every object has this property, but it can be null.
Sharing Data Between Objects via a Prototype.
Getting and Setting the Prototype:: Object.create(proto, propDescObj?), Object.getPrototypeOf(obj).
Object.getOwnPropertyNames(obj) returns the keys of all own properties of obj.
Object.keys(obj) returns the keys of all enumerable own properties of obj.
a property is virtual and not storage space.
Accessors (Getters and Setters) by Property attributes(2 methods) or property descriptors(Object.create & Object.prototype)
Property Attributes:: Value, Writable(1|0), Get, Set, Enumerable(1|0), Configurable(1|0).
The general rule is that properties created by the system are nonenumerable, while properties created by users are enumerable.
The main purpose of enumerability is to tell the for-in loop which properties it should ignore.
Protecting Objects:: Preventing extensions(impossible to add properties to obj), Sealing (makes all properties “unconfigurable”/read-only) & Freezing (all properties nonwritable and seals obj)
Protection:: it affects the own properties, but not the values of those properties.
constructor:: It is a normal function, but it is named, set up, and invoked differently.
Object.create():: only uses the prototype and not the constructor.
objects are often used as maps from strings to values.
Inheritance:: for-in give u all properties + the inherited object.
Object.keys(obj):: lists only own properties and enumerable.
the property __proto__ is special nd resreved.

############# JSON ##############

JSON stores data as plain text.
Compound:: Objects of JSON data and arrays of JSON data
Strings & Property keys must always be double-quoted.
JSON.stringify():: translates the JavaScript value to a string in JSON format.
toJSON method by JSON.stringify() to obtain a value to be stringified, EX:: JSON.stringify({ toJSON: function () { return ‘Cool’ } })//'”Cool”‘
JSON.parse():: parses the JSON data in text and returns a JavaScript value.

########## Mascenalous ###########

URI characters: ; , / ? : @ & = + $ # // encodeURIComponent(uriComponent) vs decodeURI(encodedURI).
eval() Versus new Function() to evaluate code.

Leave a Comment