Js Basics Flashcards
Javascript engine
Ideally interprets the code
But modern browsers do just in time compilation which leads to better performance
String functions
charAt() includes() startsWith(), endsWith() toUpperCase() substr(startIndex, count) slice(startIndex, endIndex) string.padStart(5, '-') - makes the length to 5 adding - as prefix trim(), trimStart(), trimEnd() split() - converts to array
Map
const map = new Map() map.set(key, value) map.get(key) map.size map.delete(key) map.clear() map.keys() map.values() map.entries()
Set
const set = new Set() set.add(value) set.has(value) set.size set.delete(value) set.entries() set.values() set.keys()
error handling
throw 'my error' throw new Error('my error')
console
console.error
console.debug
console.table
console.count(‘key’), console.countReset
console.time(), console.timeLog(), console.timeEnd
strict mode
‘use strict’;
can be used at function level also
dom content loaded
window.addEventListener('DOMContentLoaded', ()=>{})
difference between var, let
var is hoisted and scoped to function
let is hoisted but in dead temporal zone so not accessible also it is block scoped
Array
const arr = new Arr(10).fill(0) - fill the array of size 10 with 0s
Data types in js
- Seven primitive data types:
-
number
for numbers of any kind: integer or floating-point, integers are limited by±(2531)
. -
bigint
for integer numbers of arbitrary length. -
string
for strings. A string may have zero or more characters, there’s no separate single-character type. -
boolean
fortrue
/false
. -
null
for unknown values – a standalone type that has a single valuenull
. -
undefined
for unassigned values – a standalone type that has a single valueundefined
. -
symbol
for unique identifiers.
-
- And one non-primitive data type:
-
object
for more complex data structures.
-
Thetypeof
operator allows us to see which type is stored in a variable.
- Usually used as
typeof x
, buttypeof(x)
is also possible. - Returns a string with the name of the type, like
"string"
. - For
null
returns"object"
– this is an error in the language, it’s not actually an object.
Type conversions
The three most widely used type conversions are to string, to number, and to boolean.
String Conversion
– Occurs when we output something. Can be performed withString(value)
. The conversion to string is usually obvious for primitive values.
Numeric Conversion
– Occurs in math operations. Can be performed withNumber(value)
.
The conversion follows the rules:
Boolean Conversion
– Occurs in logical operations. Can be performed withBoolean(value)
.
Follows the rules:
| Value | Becomes… |
| — | — |
| 0,null,undefined,NaN,”” | false |
| any other value | true |
Value | Becomes… |
| — | — |
| undefined | NaN |
| null | 0 |
| true/false | 1 / 0 |
| string | The string is read “as is”, whitespaces (includes spaces, tabs\t, newlines\netc.) from both sides are ignored. An empty string becomes0. An error givesNaN. |
Nullish coalescing operator ‘??’
The result of a ?? b is:
if a is defined, then a,
if a isn’t defined, then b.
In other words, ?? returns the first argument if it’s not null/undefined. Otherwise, the second one.
Strings
Strings are immutable
index of
lastIndexOf
Includes()
Startswith
Endswith
Slice(start, end)
LocaleCompare for comparison
Trim - trims from beginning and end
Weakmap and weakset
Similar to map and set but keys need to be object and allows for garbage collection.
XMLHttpRequest
const req = new XMLHttpRequest(); req.addEventListener('load', function (){this.responseText}) req.addEventListener('error', function (){this.responseText}) req.open('GET', 'url'); req.send();
fetch
const headers = new Headers(); headers.append('Content-Type', 'application/json') const result = await fetch(url, { method:'POST', body: JSON.stringify(bodyObject), headers })
new FormData(form)
const abortController = new AbortController() abortController.abort(); fetch(url, {signal: abortController.signal})
Web workers
A browser API for running scripts in a separate thread from the main execution thread.
A worker object is created with the Worker(filePath) constructor function. The argument to this function is a path to another JavaScript file that will run in a separate thread.
Workers can send messages back and forth with the main thread via the postMessage(message) method and the onmessage event. For example:
// main JavaScript file const worker = new Worker('worker.js'); worker.postMessage('hello'); worker.addEventListener('message', (event) => { console.log(event.data); // 'world' });
// worker.js postMessage('world'); addEventListener('message', (event) => { console.log(event.data); // 'hello' });
In general, most workers are dedicated workers, meaning they can only communicate with the script that created them. However, a SharedWorker can also be created to share a worker with multiple tabs or iframes. That said, SharedWorkers still do not have widespread support across browsers.
Custom event
// Create the custom event const myEvent = new CustomEvent('myCustomEvent', { detail: { message: 'Hello, world!' } }); // Add an event listener for the custom event document.addEventListener('myCustomEvent', function(event) { console.log('Custom event triggered:', event.detail.message); }); // Dispatch the custom event document.dispatchEvent(myEvent);