Notes
JavaScript Speed Course - Learn JavaScript in ~75 Minutes
Section titled “JavaScript Speed Course - Learn JavaScript in ~75 Minutes”Questions in the video
- Running Js
- In Browser
- How to run js from browser using html script tag?
- How to reference .js file in script tag?
- Using Node.js
- In Browser
- string interpolation in js | template literals or template strings
- npm package
prompt-sync-> for collecting user input in console i.e. without browser - Import file in js in node env is
const prompt = require(prompt-sync) - Data Types
- string
- boolean
- number
- undefined -> it is a type as well as only value allowed in that type
- null -> it is a type as well as only value allowed in that type
- Variable Type
- var -> Function scoped, Hoisted
- let -> Block scoped
- const -> Block Scoped
- Arithmetic operations on different types
- Type cohesion -> When different types are used in arthimetic operations, js tries to convert the types to do the operations
- adding number + string = String concatenation e.g.
1 + "1" = "11" - number + boolean = number e.g.
1 + true = 2 - number + boolean = number e.g.
1 + false = 1 - string + boolean = string concatenation e.g.
"hello" + true = "hellotrue" - string(number) * number = number e.g.
"123"*2=246 - number / string(number) = number e.g.
123/"3"=41 - string * number = NaN e.g.
"hello"*2=NaN| Nan -> not a number
- Type conversion
- String to number.
Number("123") = 123orparseInt("123") = 123 - Number to string.
String(123) = "123"or123.toString() = "123" - Boolean to number.
Number(true) = 1orNumber(false) = 0 - Number to boolean.
Boolean(0) = falseorBoolean(1) = true - String to boolean.
Boolean("hello") = trueorBoolean("") = false - Boolean to string.
String(true) = "true"orString(false) = "false" - string to float
parseFloat("12.2")=12.2
- String to number.
- Logical operators
==-> equal value | loose equality operator- Performs type cohesion
console.log(null==undefined) -> trueconsole.log("1"==1) -> trueconsole.log(1=="1") -> trueconsole.log(1=="true") -> falseconsole.log(NaN==NaN) -> falseconsole.log(undefined == null) -> trueconsole.log(0 == false) -> trueconsole.log(1 == true) -> trueconsole.log(null == false) -> falseconsole.log(""==[]) -> trueconsole.log(0 == []) -> trueconsole.log("1,2"==[1,2] -> true
===-> equal value and equal type | strict equality operator!=-> not equal value!==-> not equal value and not equal type&&-> and||-> or- Exceptions
console.log("hello" || true) -> helloconsole.log("" || true) -> trueconsole.log("" || false) -> false
- Exceptions
!-> not
- Switch statement
- Switch automatic fallthrough -> need to use
break;otherwise it runs next case available
- Switch automatic fallthrough -> need to use
- Arrays
cosnt arr = []arr.lengthto get length of arrayconst arr = [1,2,4, true]-> Type of array can be differentconst arr2 = new Array(5)const arr = Array.from("hello") -> ['h','e','l','l','o']- Access element that is not existing it give
undefined. e.g.let a =arr[arr.length] - Assigning value to index that doesn’t exist -> works just fine e.g.
arr[10] = 5andarr.lengthbecomes 11, the values become[ <1 empty item>, 2, 4, true, <6 empty items>, 5 ] arr2.push(12)-> appends at endarr2.pop()-> last element get poppedarr2.shift()-> Removes the first element from an array and returns it. If the array is empty, undefined is returned and the array is not modifiedarr2.unshift(5)-> Inserts new elements at the start of an array, and returns the new length of the arrayarr2.indexOf('t');Returns the index of the first occurrence of a value in an array, or -1 if it is not present.arr2.lastIndexOf('t');arr2.includes('t');-> returning true or falsecosnt arr3 = arr2.concat(arr)-> Concatenate both the arrayscosnt str = arr2.join(",")-> returns string after joining the elements by,arr2.slice(starIndex, endIndex);-> return sliced arrayarr2.splice(starIndex, deleteCount);- Removes elements from an array from start- De-structuring
const [x,y] = [1,2]->console.log(x,y)const [x,...y] = [1,2,3,4]->console.log(x,y)| Spread operator is used foryand nowywill have [2,3,4]
- Copy of array
const x = [1,2]const y= [...x]-> both x and y will have different reference
- Map | Filter | Reduce
// Mapping numbersconst numbers = [1, 2, 3, 4];const doubled = numbers.map(num => num * 2);console.log(doubled); // [2, 4, 6, 8]
// Mapping user namesconst users = [ { name: "Alice", age: 25 }, { name: "Bob", age: 30 }];const names = users.map(user => user.name);console.log(names); // ["Alice", "Bob"]
// Reducing array to sumconst numbers2 = [1, 2, 3, 4];const sum = numbers2.reduce((acc, num) => acc + num, 0);console.log(sum); // 10
// Filtering even numbersconst numbers3 = [1, 2, 3, 4, 5];const evenNumbers = numbers3.filter(num => num % 2 === 0);console.log(evenNumbers); // [2, 4]- For loop
for(let i=0; i<arr.length;i++){}for (const element of arr) {}for (const [index,value] of arr.entries()) {}
- Objects
- JSON -> Javascript Object Notation
const obj = {}const obj = {key:"value", key2: "value2"}const obj = {key: "value", method: function(){}}- Accessing value ->
obj.keyorobj["key"] - Delete value ->
delete obj.key|delete obj["key"] Object.keys(obj)-> return all keys in arrayfor (let key in Obj) {}-> Notice for objects we use in for iterables we use for in for loopObject.values(obj)-> return all values in arrayObject.entries(obj)-> returns array of array with key and value. e.g.[[key,value],[key2,value2]]Object.assign(obj, {key3:"value3"})-> adds key and value to obj- De-structuring
const {key,key2} = objconst {key, ...rest} = obj| rest contains rest of key-value pair of obj
- Copy of object
const x = {a:1, b:2}const y = {...x}
JSON.stringify(obj)-> Convert object to stringJSON.parse(obj)-> Convert string to object
- Sets
const set = new Set()const set = new Set([1,2,3])set.add(4)|set.delete(12)|set.has(3)|set.size|set.clear()|for (const item of set) {}- Get array from set. e.g.
const arr = [...set]
- Map
const map = new Map();map.set("key", "value");|map.get("key");|map.delete("key");|map.has("key");|map.size|map.clear();|for (const [key,value] of map) {}- convert map to array
const arr = Array.from(map)->[[key,val],key,val]
- Error Handling
try{} catch(err){ } finally{}throw new Error("error message")-> throw custom error
- Functions
function functionName (param1, param2){ }const functionName = function(param1, param2){}const functionName = (param1, param2) => { }| Arrow functionconst geet = (name) => { return ()=> name }-> call it likegeet("hello")()- Rest Parameters -> accept any number of parameters
function addNums(...number){}
- This Keyword & Scope
- In object method it refers to current object, but only works in standard function but not in arrow function we get undefined in that case. -> Reason : Arrow function actually inherit this at the time of definition not when they called. so it calls from global scope and if in global scope there is no variable it spits out undefined
const person = 1 name: "Alice" greet: ()=> { console.log(Hello, my name is ${this.name}*); },person.greet(); // Hello, my name is undefined- Promises A promise in JavaScript represents a value that will be available either now, later, or never. It helps handle async tasks without callback hell. It has three states: pending, fulfilled, rejected.
// A function that returns a promisefunction fetchNumber(num) { return new Promise((resolve, reject) => { setTimeout(() => { if (num > 0) { resolve(`Success. Number is ${num}`); } else { reject("Number must be greater than zero"); } }, 500); });}
// Calling with then and catchfetchNumber(5) .then(result => { console.log("Then Catch Result:", result); // Output: Then Catch Result: Success. Number is 5 }) .catch(err => { console.error("Then Catch Error:", err); // Will not run here });
// Calling with async and awaitasync function run() { try { const result = await fetchNumber(10); console.log("Async Await Result:", result); // Output: Async Await Result: Success. Number is 10 } catch (error) { console.error("Async Await Error:", error); }}
run();
// Using Promise.allconst p1 = fetchNumber(3);const p2 = fetchNumber(7);const p3 = fetchNumber(9);
Promise.all([p1, p2, p3]) .then(values => { console.log("Promise.all Results:", values); // Output: Promise.all Results: [ // "Success. Number is 3", // "Success. Number is 7", // "Success. Number is 9" // ] }) .catch(error => { console.error("Promise.all Error:", error); });- Other available method for promise
Promise.allSettled-> Waits for all promises to finish, even if some fail.Promise.race-> Returns the result of the first settled promise, success or failure.Promise.any-> Returns the first fulfilled promise. Ignores rejections. If all reject, it throws an AggregateError.Promise.resolve-> Creates an already resolved promise.const p = Promise.resolve(100);