Advanced JS
Function Expression vs Function statement vs IIFE
iffe (xyz()) is same as ((xyz)())
THIS
When 'This' is defined in object, it refers to object's env & everywhere else it refers to global variable
- but but but if function is inside an object, it again refers to global this
- so output
updated c object
updated c object
- to resolve above problem put this = self above console.log Below is an screenshot
Functions are first class members in JS
Functions are plain JS objects with added superpowers : it can do allobject things +
- the code you write inside fun sits in a special property called 'code' which is invocable - meaning , will have an execution context
- when we call fun() -> it invokes the code we have written
- it has an optional name property to distinguish from other functions
Coercion
console.log(3<2<1) \\true
Why?
- Coz if you see above table it starts reading from ltr in case of < & >
- so it meas it will be evaluated as
(3<2) <1
, 3<2 == false , sofalse <1
, - Coercion takes place here meaning
Number(false) <1
=> 0 <1 ==> True
Operator Precedence
a+b*c/d : Precendence is decided by below table
Answer: 4,4,4 This happens because of precedence. it goes from right to left. if precedence was from LtoR answer would be 2,2,2
View All precedence here MDN
Notations
+( 3, 4) //Pre fix notation
( 3, 4)+ //Post fix notation
3 + 4 // In fix notation - JS makes it eaasy for us to write code in this way using In fix notation
Async Functioning
In the above code, when clicked immediately after page reload, result is below:
🤔 Reason?
JS first finish processing || Stack and then goes to queue =
so all the events like clicks etc are placed in queue and js takes times to finish all execution context (functions) and then go to queue.
Objects & Functions
- Both are same