0% found this document useful (0 votes)
13K views209 pages

Javascript Weird

1) Syntax parsers analyze source code syntax to convert human-readable code into machine-readable code. Errors occur if the syntax does not match compiler expectations. 2) Code exists within lexical environments like functions, where variables are stored. Global code exists outside any functions. 3) Code execution is managed by an execution context that controls the order and environment of code execution. Multiple programs work together to execute code in its proper context.

Uploaded by

Adnan Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
0% found this document useful (0 votes)
13K views209 pages

Javascript Weird

1) Syntax parsers analyze source code syntax to convert human-readable code into machine-readable code. Errors occur if the syntax does not match compiler expectations. 2) Code exists within lexical environments like functions, where variables are stored. Global code exists outside any functions. 3) Code execution is managed by an execution context that controls the order and environment of code execution. Multiple programs work together to execute code in its proper context.

Uploaded by

Adnan Khan
Copyright
© © All Rights Reserved
Available Formats
Download as PDF, TXT or read online on Scribd
Download as pdf or txt
Download as pdf or txt
You are on page 1/ 209

1) Syntax Parsers

Syntax we write is compiled; human readable to


machine readable, if syntax doesn’t match it doesn’t
mean anything, so syntax is analyzed/parsed by
complier.
2) Lexical Environment
The vocabulary we give sits in the functions inside,
so there is an environment for lexical sitting.
3) Execution Context
The code we give is executed by several other set of
programs, so the context is broad of execution.

Name Value Pair


Every name has a value is called name value
pair. Name has other names, which has
values, like name has a list of names which

have values.
Global Object
which not inside a function.
This is global, in chrome, window
is global.

Hoisting
Before running code, memory
space is allocated; due to this the
preceding code may run before
the succeeding dependent variable etc. code.

If a variable is not defined then it is undefined , it is a value


check in app.js
var a = 'hello world';
console.log(a);

if (a === undefined) {
console.log('a is not defined');
}
else {
console.log('a is defined');
}

Single threaded:
One command executed at a time.
Synchronous:
One at a time, one line of code at a time, There is a
sequence/order of things happening, Waiting for one step in
order to execute other.

Invocation:
Running or calling a function by parenthesis ()

Variable Environment: where they live:


1st variable global displays, then
function (a)
first gives its own 2 and then function (b)’s undefined
lastly, it again, gives the global value.

The Scope Chain


It gave 1, the value sitting at the global level.
Every execution context has a reference to outer context. In a
lexical environment, if an execution context does not find a
variable, it will look outside, down in the stack. In this case it
sits down to global context.
If there are several functions calling each other, it will keep
looking down until it hits the down global. That whole chain is
called Scope Chain.
Scope is where can I look for variable and chain is links to outer
environment.
Scope: where a variable is available in your code.

Asynchronous: More than one at a time.

Click event came in the end, because clicking input came


through HTTP to JavaScript sequence coding, and it executed
after completing the stack.

Dynamic Typing
You don’t tell the engine what type of data a variable holds, it
figures it out while your code is running.
Variables can hold different type of values because it all figured
out during execution.

We define type of variable in other language, like Boolean.

Types of data which can be stored in variables, we don’t declare


it though but it has Six Primitive types:

Primitive type: that represents a single value, and it is not


an object, because object is a collection name value pairs.

1) Undefined
Lack of existence (shouldn’t set a variable to this)
2) Null
Lack of existence (should set a variable to this)
3) Boolean
True or False
4) Number
Only one numeric type in JavaScript, floating point
number.
5) String
sequence of characters, can be inside single or double
quotes.
6) Symbol –new type, ES6

Operators
A special function that is synthetically written differently. It
takes two parameters and returns one result.

Var a = 3 + 4;
Console.log(a);

Writing between the parameters + is infix notation.

Operator Precedence
Which operator function gets called first.

Operator associativity
What order operator gets called in: Left to right or Right to left
This means when the functions have the same precedence.
Var a = 3 + 4 *5;
Console.log(a);

JavaScript operator precedence table can be found on internet,


also in pdf.

Multiplication precedence num: 14


sub precedence number: 13, hence * called first.

Var a = 2, b = 3, c = 4;
A = b = c;
Console.log (a);
Console.log (b);
Console.log (c);

What number will be the output, 2 3 or 4.


answer is, it depends upon associativity because precedence of
= is same..
Output: 4
Associativity is right to left.

() grouping precedence is the highest.

Coercion: converting one type to another.


if a number is in string it will be string.
1+’2’ is 12, not 3.

Comparison Operators
Console.log(1<2<3);
It will give True.
But
Console.log(3<2<1);
It also gives True.
Reason:
Associativity of < operator is left to right, so 3<2 is false
so it becomes, false<1 gives true
Because value of false is zero, and zero is less than 1.

Additional knowledge
This is negative side of javascript, especially double equal.
Solution:
Tripe equal === doesn’t coerce.

Difference
Use triple equal when comparing operators.

Existence and Booleans


Nothing comes in console
we can use coercion for our advantage like associating null

It still gives nothing


As when we type hello instead of null it gives, something is
there.
When a 0, it also gives nothing, so the solution for zero is.

Now it gives something.

=== will be run first than || operator

A===0 returns true


false || true returns true (because a = 0, so a becomes false)
A behaving as false, undefined null is zero that’s is false
So we used coercion for our advantage.

Default Values
When no argument inside function given what happens?
Remember: operators are just functions that return values.
It returns the value that can be coerced to true.

It coerced from left to right when both true.


It coerced the true one.

So what will happen now


Framework
Framework and library are two different things, but for here we
assume both the same, as both perform a task and intended to
be reusable.
We had one app.js in source, but we can make several files
using as libraries as lib1 and lib2.

Lib1
Var labraryname = lib1;

Lib2
Var labraryname = lib2;

App.js
Console.log(libraryname);

Result:

Lib1 and lib2 file’s variables were were treated as global


variables sitting in global execution context, last variable value
was lib 2, so app.js gave in console lib2 value.
We might have collided with other library or other library has
replaced us.
Solution:
we may check whether a variable is already there in another
library before defining it.
Suppose, we want to use variable libraryname in lib2 file and
we want to check whether the variable is pre defined in
another library.
Lib2 typed

Window or this is global variable, as discussed previously.

Result:

We found that libraryname variable is there in lib 1 file.


OBJECTS

Objects can be Boolean or number, it can be a object property


like child of object or it can be a function attached to object
called function method.
Objects sits in memory and have a reference number.

Adding objects
One way to create an object to memory is this new Object.
We need s variable to fish the firstname from the object using
[].

Dot operator
Dot operator is equal to [] operator, however in [] operator
“double quotes are used.

These Operators are used for showing the data and feeding the
data.
Dot operators are preferred.

Object literals
We can use {} operators instead of new Object function.
Var person = {}; ➔ var person = new Object();
They do same thing.
{} operator is faster way then new object and dot operator
adding object.

Javascript is very liberal in using whitespace.

Like
Var person = { name: ‘adnan’, surname: ‘khan’} ➔

Var person = {
name: ‘adnan’,
surname: ‘khan’
}
Address is another object.
Adding in flying, displaying and adding.
\

Adding objects:
Javascript has no namespace feature, but we can fake it.

We don’t have containers but we have objects.


How to prevent this collision?
Or put it this way
Announcing it empty first.

Or this way
The idea is that I have contained my properties, variables inside
a container object.

JSON is inspired by javascript literal syntax. However, there is


difference and people mistake understanding it the same thing.

Let’s take a JavaScript object literal and convert it to JSON


object through JSON.stringify method.
And then
\
And then taking a JSON value and convert it to Javascript object
literal.
Primitive values, objects and other functions can be added
Code is also a property and sits in a function. However, code is
invocable.
Like we add values to variable, we can add to functions too.

We just attached a property to the function like we attach to


any object with dot operator.
Expression→ returns a value
Statement only works and does not return a value, like if
statement.
This function also is a statement. It gives values when executed.

Another way is function as an object and stored in memory.

Here the function does not have any name, then how to
invoke? There is a variable associated with it so it can be
invoked with var name as follows.

How to invoke?
an

However if anonymousGreat(); is called before the variable


defining, it returns undefined error, because the variable is not
a an expression but associated to a function, and before
execution java in hoisting saves only memory objects, values.

Function log(a) {
Console.log(a);
}

Execution
Log(3);
Gives value 3

Var b=3
Log(b);
Log(“Hello”);

Var b = “hello”;
Log(b);

What about an object? – creating object on


a fly.
Log({
Greeting: “hi”
});

Creating function on a fly.


Function log(a) {
Console.log(a);
}

Log(function() {
Console.log(‘hi’)
});
We passed a function to a function.
Function is an object, they are first class functions.

How to run this function?


A programming language is said to have First-class
functions when functions in that language are treated like any
other variable. For example, in such a language, a function can be
passed as an argument to other functions, can be returned by
another function and can be assigned as a value to a variable.

Just replace here ( a() instead of log(a))

Function log(a) {
a();
}

Log(function() {
Console.log(‘hi’)
});

This way ‘a’ a is invoked, instead of a we write a function as a


paremeter.
Values and references are regarding variables.
These two variables a and b are referenced by value and holds
two different spots on memory.

Same for objects, when variables associated with objects but no


new objects created, gets same reference in the memory.
So by value is different than by reference.

Changing a will not affect b and remain 3, because they are two
different value spots in memory.
A will return 2 and b will return 3 in console.

// by reference (all objects (including functions))

Var c = {greetings: ‘hi’}


Var d;
D=c;
c.greeting = ‘hello’ // mutate
console.log(c);
console.log(d);

Both pointing to the same object so one changes makes


another change.

Lets make another function


Here we replaced greeting value to Hola, now if we console d or
c, we wil get hola and not hello which is the previous value.

= sign

= sign created new value in the memory, and gave howdy.


This is a special case where by reference does not really apply.
C = {greetings: “howdy”}
When c found that this is pre exising value but second value
does not exist it created value. But d still remains attached to c
the old value.
This points in various ways.
In this case, This points to window object, which is a global
object.

Now what if we function expression equal to value.


It is still window

This.newvariable makes a global variable newvariable and


results hello in console statement.

Creating a method
Remember if the value is a primitive it’s a property and if the
value is a function is called a method.
Var c = {

In this method function, this points to the object c. log is a


function here.
This.name, has updated the entry of name value, inside the
object c.

Now a bug in javascript


Function inside a function does not work, this gives a global
variable of this, creates a global object.

Then whats the solution foir the bug

We defined self=this;
This way bug dispelled.
Self pointing to our whole object.

Mutated successfully.
ARRAY

This is different, because in other languages arrays are


collection of items of one type, number Boolean etc.
But in javascript it is a mix of all type as above.
In the end, function is called, as it is on number 3, and
arugment is passed of item number 2. This is amazing.
ES6 uses sperads instead of arguments.
Arguments hold all the parameters that are passed to
functions.
No arguments passed in this parameter, so output will be
undefined

Default parameters can be also set,


Function greet (firstname, lastname, language) {
Language = language || en
}

If language parameter is not given it will give en in output.

If we want to see arguments given, in every function we call in


the end it gives arguments in form of array.

0300 5706377 mian naseer.


… other takes everyparameter.
We don’t have function overloadig in javascript but
we have first class functions, calling function inside
functions.
Function overloading: function with the same name
have different number of parameers. That does not
work in javascript as functions are objects.
Javascript parser is very liberal in white space.
Observe the white spaces.
Immediately invoked function expressions.

IIFE
The variable greeting does not touch the global context and
that makes it a useful approach.

Lets make another js file


Greet.js has the same variable as in app.js function, that’s
collision, however, the output is of app.js hello john, and not of
global variable.

But if we print the greeting variable then output will be there


so no collision.
Console.log(greeting);
Both files exist in separate execution context.

The value of greeting, the global variable is halo, but we can


change its value inside the function,
Suppose we change it from hola to hello.
Here window is the global object, but it may not be in other
case, where we may change the global object.

Hola changed to hello.

It is notoriously difficult topic to understand.


Some unusual is happening, how does the sayhi function still
know the whattosay variable

It is possible because of closures.

What is happening under the hood?


The execution context is gone but, whattosay ‘hi’ remains.
What happens to this memory context when the execution
goes away?
Sayhi function executes return tony, and then javascript goes
out to the lexical context to find whattosay, which is in
memory, and then whattosay and name is added as in return.

In order to preserve the value of a separate execution context


Let’s have another example
Fs[0]()
Fs[1]()
Fs[2]()
All functions upon calling gives the same value 3, stored in
memory, as it approaches to outer memory.
It only tells hats the memory right now, not at the time it was
created.

Free variables are functions that are outside the function but
have access to.

It does not save the value while execution.


So, how to solve the issue?

In ES6 the solution is very easy, with let.


Every time the loop runs, the j variable makes a new memory.
Each time called each time different spot of memory.

But, how to do that with ES5?

We need a parent scope to hold the current value.


We can execute a function on fly to perform the task.
We created a function j and give it i
Every time the loop runs it will execute the function, passing 0,
1 and 2 to I inside the function j.
With the clousure it will hold the function after execution.
The function executed is returned and pushed into the array.
The j does not go out to the whole loop, instead it goes out to
the highlighted execution context, giving (i) and returned in
console in form of function j. because j stores the value at time
of execution.

A closure occurs when a variable or function defined inide of


the inner function’s scope continues to be accessible to the
outer function even after the inner function has returned. Just
about the exact opposite of what you said.
How we can use closures to our advantage for making patterns
that would be otherwise impossible.
Lets create a function factory.
Function factor: that returns or make something
Makegreeting is a function factor insife the greeting function
Closures and callbacks
We use clousres in jquery too.

In function we can put any.

making it a comment
Callbacks are a simpler concept. A
callback is basically where a function
accepts another function as a parameter.
A function that takes other functions as arguments or returns functions as its
result is called a higher-order function, and the function that is passed as an
argument is called a callback function. It’s named “callback” because at some
point in time it is “called back” by the higher-order function.

Callbacks have many everyday usages. One of them is when we use


the setTimeout() and setInterval() methods of the browser’s window object –
methods that accept and execute callbacks:

I'm trying to pass some parameter to a function used as callback,


how can I do that?
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}

function callbackTester (callback, param1, param2) {


callback (param1, param2);
}

callbackTester (tryMe, "hello", "goodbye");

This would also work:

// callback function
function tryMe (param1, param2) {
alert (param1 + " and " + param2);
}

// callback executer
function callbackTester (callback) {
callback();
}

// test function
callbackTester (function() {
tryMe("hello", "goodbye");
});

Callbacks are a way to make sure certain code doesn't execute until other code has
already finished execution
There's no reason to use a callback unless you want to bind something to an event
handler, or your operation is potentially blocking and therefore requires an
asynchronous programming interface.

CALLBACK is a function that is passed to another function as an argument.

There are lots of structures for call backs.


Another way to write variable a is

Another way is
Replacing the first part function show with the last part geeky
function
Controlling this

This variable controlling, through apply and bind command.


All three call, apply bind has to do the “this” variable.

This keyword pointing to the object person here.


Lets create another variable “logname”
However, the this will fail, why?
Because this is pointing to a global object and there is no such
global object as getfullname var.
Controlling the this variable!!!

We will create another variable logpersonname, and associate


it with bind logname
Note: All functions in javascript gets access to these three
methods, call bind and apply. We bind the variable to the
object we want.
Bind actually copies the logname to person.
So we have changed the execution context of javascript.
Now we can create a function on fly by bind and that works too

Making changes, adding parameters


Call!!
Call directly exexcutes the function without copying it in a
single step.

Apply does the same


Error because
The apply method needs to be in an array of parameters
Another way of calling it is.

Scroll down, and apply it in real life example


Invoking person getfullname, setting this key word of person to
person2 object.
So using the person method for calling object of person2
Function currying
What happens when u pass parameters to it.

we use bind here. We are multiplying two as variable a to the


function multiply. And passing 4 as b variable as parameter.
Passing no parameter

In this case a and b are passed, so the parameter 4 is just an


extra one.
Underscorejs is a javascript library, we take ready functions
from java, which are not available in browser.
source code of these libraries can be read.
The library downloaded underscore.js
Starts with a function, enclosed the code in immediately
invoked function

included
All the methods available
This is in all languages
This is javascript special. Prototype
Obj.prop2 and obj.prop3 does not find the object property.
Because the prototype is like an object inside an object
How to return, this way of objj2
John now inherits from person, as we made john prototype of
person.

Lets print it
Another object will have only first name
First this points to jane and second this to default
Lets use for, and loop over every member in john
We are not using doe but [] ith john, which accepts strings as
the property name.
Prop will be the name, and then Prop will be used to grab the
value of the name.
Getfullname is the property too, last one, but that of person.
What if we want specific john properties only?
Or we can use the variable, if we need all the properties in john
We make these new objects, jane and jim, and want to copy
them to john. How? By extend
__.extent (object to be extended, addition, addition)
We can learn from open source, just extra thing
For learning watch video

A class in java is not an object but it defines an object.


The new keyword is used to create a new object from that
class.
The new word is an operator, with new an empty object is
created, and then function is called.
This variable pointing to the empty object. Whatever is done
with the this object, it will be returned to the empty object.
If we do not do anything, and only write this in console, empty
object is returned
Constructing an object via function, so we use this kind of
function creating n object is a function constructor.
Now if we want first name and last name as we want we will
set paramerts
When we set the function constructor we have already set the
prototype.
The prototype property of a function is used only when building
objects, means constructor function.
With __. We can access prototype.
The prototype proprty of the function is not the prototype of
the function, its prototype of the objects created, using
function as a function constructor.
Now interestingly, the object contructor connects to the
prototype, suppose we created two objects, person john and
jane, it will be the prototype, and we made a method of the
prototype in person, so
Jane and john = Prototpe person
We set another method
This searche for proto in john, which is not found, then it
searches for its own propt, which we defined as propo person
methd, getfullname, so it take names from it.
Ok, why don’t we add getfullname method to the object
person? No, because of memeory, if we have thousands of
copies new objects of person, it will have thousand copies,
large memory required.
But with prototpy, it takes only one space.
What if we forget the keyword new?

It ill give undefined


And it didn’t go to prototype because it is undefined and not an
object.
There is a convention of using first capital letter of the
constructor function, so it reminds the new keyword if we have.
There are built in function constructors in javascript, for
example we make a variable, and it is not a number, because it
is an object.
It is not s tring, when we treat it as a a string, but it is an object

Object which contains primitive, and itself is not a primitive,


like a string or a number.
Primitive to string coversion through prototype
This is true, limit, which is number of letters is less than length
of the string is true, is a method.
We use prototype in frameworks like a feature should be
available to everyehere.
Error because javascript nice enough to convert string to an
object, does not convert numbers to object but we can do this
ay

Array
An array is an object!!!!
We may use it like an object!
Arrays are a bit different than are in other languages.
O,1,2 are the property names and john, jim, jane are values.

When we write a prototype and use for loop with “in”


The problem is that,
Solution is to use “i” in for loop insteas of in
Another way to create an object is this.
You can create one object that is the basis of all other objects.
But this object.create is not available in older browser, so what
to in such a project?
Answer
Engine:browser

We can add this code, if object.create is not available, the code


runs
Class unlike in other languages is an object in JS.

Another concept of creating objects in ES6 is classes.


Trying to mimic other language to appease other coders.
Ok, now how to set the prototype?

Through Extend!!!! Prototype


The word super would call the constructor of the object, that is
my prototype

Class is just syntactic suger.


ES6
Live practicing tools
Helper Methods: set of helpers built into array object,
specifically,filter, find, reduce etc, previously applied through
libraries but now a part of the browsers.
All different helper methods
Avoid for loops and use helper methods instead!
Use forEach helper instead of for loop!
For loops are prone to mistakes, instead foreach is easy. It
works with an iteration anonymous function

Goes down to green and then blue


We can make it differently by making the separate function,
passing the function as a paremeter in forEach helper

Now the adder function repeats itself.


Case

Map
We don’t need a separate blank array in map method, it makes
its own array.
Cars is an array of objects.

Filter
Another
Here post id 3 is ignore because we don’t have it in post
variable
First we make a function which contains both, post object and
array of comments, before filter method, and then we filtered
comments, if post id matches.

Find
Break statement
Filter function
Another example

With this we added model property to the car object.


Another example is
Having two parameters

Practical example
The every and some helper
With every there is and & operator and with some there is || or
operator
If there is a form filling, we make sure user type something we
make use every and some
What if the form is very big with tens of entries, so we cannot
use && functions for all

Addition
Zero is the initial value passed to the iterator.
How to get an array of colors only, we can do this with map
filter also.
We supposed previous with an empty array in the end.

The split() method is used to split a string into an array of substrings, and
returns the new array.
We have splitted the string in empty character “ ”, creating an
array and the reduced it, and no we will pass the function
deciding what to do with the reduced array.
After giving the previous and char (pre defined in js), we gave a
counter for previous is zero as e do in reduce helper.

We can use a trick with ! symbol, turning into true and false
! exclamation mark is a flip of Boolean.
In case of start with “)”, the output will be negative so it will
return negative.
Because the logic started with if, the first if statement will be
obeyed, and before doing + or – to previous it will act and
return negative. Logic power!

LETS/const
Development to ES6 from ES5 can be categorized into two
buckets, one
Syntactical changes, stuff to write you less code
Second, is about bringing new ideas, functionalities, and
constructs.
We don’t use variable var in ES6, although we can we use
instead const and let, const when the value of var doesn’t
change and let when it changes.
Advantage: it helps reading code
But we cannot change const name

The includes() method determines whether a string contains the characters of


a specified string.
We got an idea what is changing and what is not by let and
const.
Templeate string
Backtick key is with 1 key.

this is es5 now in es6

With backtick
Any valid javascript expression can be put inside.
Or one line java script
Now expanding on it

With arrow function


Remove return as well

We can remove parenthesis if we have one parameter


But we require parenthesis if we require two

Parenthesis required when no argument


Other one
How => can solve this problem in javascript

It can be solved with bind


Or self

With arrow
Enhanced literals
Now we will not write the inventory value and function
Still it’s the same thing, no need to write inventory value if
name and value the same and no no need to mention the
function word

A function which is returning objects, inventory


We return an object which creates a book shop, inventory is
an array of books, passed as an argument
Object constructor:
property name is the parenthesis is passed and then in object
name below as filler, the property name and value can be same
as a filler, and no need to put quotation.
Another example
url and data is same so we skip one

Rest operator
Numbers are passed in array, what if numbers are passed as
separate arguments.
Like this
Like this … numbers
… is the rest
Another is
Concatination method
Adding two arrays into one
We can do the same job through spread….
Adding a single item also

If there is no milk in the array, add the milk item


Making use of Rest and Spread (…) operator altogether.

What if this is a libfrary gets popular, and the demand is to


change the function name to multiply, but we want to retain
the existing calculateproduct name as well
But this is duplicate

Destructuring
Destructuring is a JavaScript expression that makes it possible
to unpack values from arrays, or properties from objects, into
distinct variables. That is, we can extract data from arrays and
objects and assign them to variables

Example, assigning properties

In ES6 we can do it simply


It can be also combined

Another
Of arrays

Works like this


Rest operator
Now array of objects instead

Location property in a different way


But I want to destructure specific location

Another example
Array inside object
First find the property locations in the object, const {locations}
=
ES5
const google = {
locations: ['new york', 'mount view', 'faint']
};

const location = google.locations[0];


location

We have a function hard to remember its arguments order,

One solution is passing on an object as argument


Other solution is to destructure the function properties

Then order does not matter when passing arguments


It is like we made an array an object
Example
We have an API giving us points, we will change it to
coordinates
First we extracted pair and then destrcuturing pair elements

With map entering in to point array, then We are pulling pair


and then pulling elements of pair but we can pull directly the
elements of the array like we did the object, and the map goes
one by one.
For arguemtn inside the function () and then [] for the array and
x and y variables for the elements pulled out

You might also like