Javascript Weird
Javascript Weird
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 === 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 ()
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.
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);
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);
Var a = 2, b = 3, c = 4;
A = b = c;
Console.log (a);
Console.log (b);
Console.log (c);
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.
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.
Lib1
Var labraryname = lib1;
Lib2
Var labraryname = lib2;
App.js
Console.log(libraryname);
Result:
Result:
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.
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.
Or this way
The idea is that I have contained my properties, variables inside
a container object.
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
Function log(a) {
Console.log(a);
}
Execution
Log(3);
Gives value 3
Var b=3
Log(b);
Log(“Hello”);
Var b = “hello”;
Log(b);
Log(function() {
Console.log(‘hi’)
});
We passed a function to a function.
Function is an object, they are first class functions.
Function log(a) {
a();
}
Log(function() {
Console.log(‘hi’)
});
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.
= sign
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 = {
We defined self=this;
This way bug dispelled.
Self pointing to our whole object.
Mutated successfully.
ARRAY
IIFE
The variable greeting does not touch the global context and
that makes it a useful approach.
Free variables are functions that are outside the function but
have access to.
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.
// 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.
Another way is
Replacing the first part function show with the last part geeky
function
Controlling this
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
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.
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
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
With backtick
Any valid javascript expression can be put inside.
Or one line java script
Now expanding on it
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
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
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
Another
Of arrays
Another example
Array inside object
First find the property locations in the object, const {locations}
=
ES5
const google = {
locations: ['new york', 'mount view', 'faint']
};