JS Fundamentals - Hardikk Kamboj
JS Fundamentals - Hardikk Kamboj
Credits : These are my notes from various JS Course : Javascript Mastery, Sheriyan coding school, Namaste JS : Akshay Saini
Socials :
Variables
Let - can be changed -> braces scoped -> cannot be aaded to window object
const - constants in js - cannot be changed
Var - can be changed ( with some scope constraints) -> scope is inside function -> adds itself to window object
Valid First characters for naming -> $ or _
Multiple same name vars cannot be there
Data Types
String - sigle, double and backticks(``) qoutes. - Can use JS in it - ${ js inside here}
Number - Number normal
Null - null value ( can be assigned)
Undefined - no defined value ( cannot be assigned )
Typeof- to know the type of data type
Object - group variables and store group of data types. const object1={ name :'John', age:25,} with dot notation to access the property.
Array -> object
Operations
-> +,-,*,/
-> modulo - %
-> exponent - ** -> comparison < > (is equal) ( true or false ),!=(not equal), = ( strict equals)`
== vs ===
5===5 -> true
5 == "5" -> true
5 === "5" -> false
Logical op
AND && -> checks all and returns the last value ( truthy) if false is encountered ( return false value)
OR || -> returns the first value (truthy) ( returns the first true) and if false then the last false value
NOT -> ! -> reverse bool value
TRUTHY VS FALSY
1, string, any other number, { }, [ ]- truthy
0, null, false, ' ', Nan, Undefined -> falsy
Switch Statements
switch(value){
case 'choice':
console.log("stiuff")
break;
default:
cosole.log("default value")
}
Ternary Operator :
if(){
}
else if{
}
else{
or
? : notation
Loops
Functions
function testing(parameter){
return parameter*parameter;
}
// call
const result = testing(argument to be passed)
// Annonomous function
// Arrow Functions
Scope
Where are the variables we make are available
block, function and global scope
// Global scope
Hoisting
JS mechanism where variable and function declarations are moved to the top of their scope before code execution.
console.log(age);
var age = 20; // only the declarations goes to the top not the value;
case 2.
var hoist
console.log(hoist);
hoist = "something"
case 3 :
function hoist(){
console.log(message);
var message = 'test';
}
hoist();
--> undefined
}
--> Test
Hoisting was done with function is time
hoist();
const hoist = () => {
console.log(message)
}
--> error
Closures
As soon as the function is done with the execution all of it's content is gone, and that's why we cannot access the local scope var outside the
function.
Function inside a function
--> Access to the var of the parent scope : due to the closures.
-> that's why we get both Hi and Hello above
-> The inner data is not getting deleted here.
Strings
types ' ', " ", ``
property string.length, string[position], Cases : string.toLowerCase(), string.toUpperCase() -> store them in a new variable as well,
String.indexOf('word') -> searchs the first substring, save it to a var as well, string.includes('word')-> true or false
Substing of a string - slice(start,end)
Split a string into single chars -split method
string.split(' '); splits it on a each character, word. -> turns into an array
Reverse - reverse method works on arrays ->
First we turn the string into an array using the split method and then use reverse method to reverse the characters.
const reversed = string1.split("").reverse().join
String.trim() -> removes the spaces : used for storing emails.
Arrays
Ordered Collection of Data
const array = ['ele1', 'el2'];
loop over array -> for loop
Array methods - push, pop, shift(remove first element of array), unshift(adds new value to the start of the array)
Array Splice and Array Slice -
Splice -> array.splice(where to add, how many to remove, what all to add) : adds or remove and
Slice -> array.slice(start,end) ->copy certains parts of an array into a newly created array.
from ( start to end) excluding end.
Array For Each :
easier way to write for loop
Does not have a return value
Array Find - returns the first value that satisfy the condition.
Array includes - checks if array includes something or not -> returns a Boolean value.
It is case sensitive
Array Reduce - iterates over all the values and computes them to a single value
No need of an external var is there
Same example with forEach and reduce method
For each :
Reduce :
Takes in 2 arguments and a callback-function value called accumulator
0 is the initial value
Objects
Objects are unordered collection of related data
In form of key-value pairs
const person = {
firstName:'john'
lastName: 'Doe'
age: '40'
car = {
brand: 'maruti'
year: 2016
color: 'red'
}
}
Object Methods
another property of an obj that is a function
Built In Methods
object.keys() -> creates an array containing the keys of an object.
Object.values() : values of the keys
Complex values -
Objects -
Even if the values are equal they point to the different location in memory.
The Newly created array using the spread operator remains unchanged, meaning it is a shallow clone.
Array.slice ( ) -> also creates a shallow clone -> creates a completely diffrent array pointing to a different location in memory.
Cloning Objects :
Spread operator ( ... )
If the car color, which is an object inside an object has to be changed, the spread operator will just keep on increasing, as we have to
mention the car obj as well in the spread operator for it to work, otherwise the car color will not change as the location we passed is
only for the outer parent obj.
Solution : This is for deeply nested obj we need a deep clone, for an obj to be a deep clone it needs to destroy all the references.
JSON.stringify( ) : Converts all the JS obj into string, thereby all the references are destroyed.
JSON.parse( ) : to turn it back into a an obj we use parse()
It is an obj but an obj that is the deep clone of the persons obj.
Shortcut
Methods :
addEventListener
getBoundingClientRect( )
hasAttribute( )
Classes in DOM :
Creating Nodes
- document.createElement("h1")
- appendChild( ) : to add it to the dom
- InnerText : to add the text to that created element
- InnerHtml : To add html to that element
Traversing :
Removing :
New Keyword
Functionality : Creates a new empty object
diffrences with normal way of creating it
For just normal creation it is not used that much.
Uses?
Can use a lot of properties of present objs as everything in JS is an Obj.
Dates
This Keyword
Used to reference the obj that is executing the current function.
Every function has a reference to it, in it's current execution context.
Cannot use in arrow function
Example :
Classes
It is SCHEMA for an obj that can save many values
Constructor is just like parameters in a function ( keys are passed inside)
Initiating a user for that class
setTimeout : -> wait certain amount of time before executing a chunk of code
clearTimeout : ->
Asynchronous Nature :
Asynchronous JavaScript
Synchronous : code is executed Line by Line and tasks are completed instantly.
There is no Time delay in the completion of the tasks for those lines of code.
Example :
Asynchronous :
Using the same example showing Async code:
Here the code takes some time to run. These task are run in the background while tge js engine keeps executing other lines of code. When the
result of the waiting gets available, it is then used in the program.
This Happens because of something known as Event Loop.
Callbacks
Data Fetching from API : Async : cannot be sure how long it will take
Sync :
Async :
The error is there because the data was not returned from the function immediately, but after 2 secs.
To make it work we use Callback ( ) functions.
pass in a callback function which will run when the data is fetched
After 2 secs we get
Callback HELL
A normal callback functionality looks like :
We will replace callbacks with promises and async await due to the callback hell.
A complicated functionality of callbacks - ex of social media app
Now as the functionality grows it becomes a lot of code to do the same functionality that is called a CALLBACK HELL!!!
This is not maintainable and also not DRY ( do not repeat yourself)
To solve this issue Promises were introduced.
Promises
They are objects that either return the successfully fetched data, or the error.
It has two parameters resolve and reject
Then keyword is used to invoke it, catch ( ) to get the error
Using the callback hell example
Multiple Promises
The calling will be changed as :
Async () Await ()
It is an easier and a cleaner way to work with promises
They look like sync functions so they are easier to write
Async functions returns promises
Await Keyword : Waits for the promises to return a result.
If you want you use await it needs to be inside an async function
This is good as we do not have to use then() or fetch()
Example
In import you can change the name of the import as well but it is not good practice
-
Extras
Object and array Destructuring
Before : An object with Multiple values has been created, this is DRY
Real Usecases :
Array
Before
After
First Class Functions
A concept which tells that you can use functions as values
You can add -ve index in array as well, it will acted as a key
Higher Order Functions
Accepting a function in parameters or returns a functions, forEach is a higher order function.
Constructor Functions
Normal function where this is used and new keyword is used when it is called