0% found this document useful (0 votes)
0 views6 pages

JavaScript

The document provides an overview of JavaScript data types, variable declarations, and conversion methods, emphasizing the importance of understanding scope and type comparison. It covers key concepts such as objects, arrays, string methods, mathematical functions, DOM manipulation, event handling, asynchronous code, and promises. Additionally, it highlights best practices for coding in JavaScript, including the use of event listeners and error handling with try-catch blocks.

Uploaded by

nelmadazk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
0 views6 pages

JavaScript

The document provides an overview of JavaScript data types, variable declarations, and conversion methods, emphasizing the importance of understanding scope and type comparison. It covers key concepts such as objects, arrays, string methods, mathematical functions, DOM manipulation, event handling, asynchronous code, and promises. Additionally, it highlights best practices for coding in JavaScript, including the use of event listeners and error handling with try-catch blocks.

Uploaded by

nelmadazk
Copyright
© © All Rights Reserved
We take content rights seriously. If you suspect this is your content, claim it here.
Available Formats
Download as PDF, TXT or read online on Scribd
You are on page 1/ 6

JavaScript

There are various data types in js as in case of many other coding languages but js is somehow
more flexible but a bit tricky with its datatypes and scope issues .

Let
Const
Var
JS is dynamically typed as we don't have to declare variable type
Var pierces scope of block

So it is important to know the types and their conversion .

Mostly you will be dealing with numbers and strings


So below are few to convert.

To integer

Let a = Number(num)
parseInt(num)
ParseFloat(num)

To string

.toString()
String()

Now comparing 2 numbers is easy but if you miss the conversion the follwing may help

The == converts both the strings into number then checks if they are equal
But === is strict check it doesnot convert but checks

Object is a collection of key value pairs


Where keys are generally the properties and are strings
And values can be any data type
Object are declared within curly braces {}
Objects can be nested within objects
Dot operator is used to acess values

Now one of the most important thing is string methods

Slice can take negative value


Substring ignores negative values
Trim can be used on shite spaces and line terminators
Starttrim trimend also available
Splits(separator)
Includes
Replace
Object types number provides less operations
So we convert it to string

Mathematics functions

Abs - absolute value


Round - rounds
ceil - ceiling values
Floor - floor value
Max , min - in an array of elements
Random - gives random values between 0 to 1

We create object of date


toString
toDateString
toLocaleString
.now() counts time from initial date
.getTime time from a specific date till now
.getDay , .getMonth
toLocaleString very useful create object inside parenthesis and declare your specifications for
time like long day name , time zone date in words etc ..

Arrays
Elements can be of different types
Shallow copy - heap
Deep copy - stack
Array produces shallow copy
Push add at last
Pop delete at last
Unshift insert at beginning
Shift delete at beginning
Slice does not change array and doesnot include last index
Splice changes the initial index and no of elements to be deleted
12345
Splice 123
Original array 45
Join concatenates array and produces string type
Array.of(a , b ,c ) creates an array of elements
Array from("hitesh") creates an array of each element
Spread most imp [...marvel_heroes , ...dc_heroes]
Spread is a better way of concatenation

Destructuring

${} best way to pass variable within a string


And {} used to pass value to anything as such a button

Var pierces scope block


() => {} If curly braces then use return
() => () Do not use return
Can take arrow function inside alse ( () => {} )()

Loops

For of
For(let e in apples)
For each
Array.forEach(e => console log e )
Map
users.map(user => user.name);
Specify a key for identification
Filter sorts out the data

DOM manipulation

document.queryselector
.getElementById('title')
.getAttribute('id')
.class
setAttribute(' parameter to be changed ie class or I'd or base that holds the value ' , ' new
parameter ' )

B.innerText shows on what is visible on website as many content are hidden by css
B.textContent print entire content without hiding anything that may not be visible in website
B.innerHTML shows inner tags also

Queryselector selects the first element

Queryselectorall returns node LIST not an array


It is used to select multiple elements which was not possible in queryselector

Getbyclassname returns values in HTMLcollection not an array

Write in script tag after body tag all the programs codes you learnt
. FirstElementChild selects first child
.LastElementChild selects Last child
Parent.child.length as parent is collection but children are elements
.parentElement

Create an elemnet
.createElement
Apply I'd class name attributes
createTextnode then .append
.innerText does the same as append overirdes previous
But after all this it won't be visible
So we need document.body.appendChild('element created ') to make it visible on webpage

Create text node is more optimised than innerText no traversing


.textcontent same as innerText
.replacechildwith to replace child or we can use append
Li : nth- child('2') to select nth child
.outerHTMl you have to take entire tag not only text
.remove() to remove an object

Events

We should not used onclick as it gives less functionality


We should rather prefer eventlistener as it gives propagation ability
.addeventlistener( any event , then function)
Can be predefined or custom

Async code
Js is synchronous and single threaded
So we async await in order to attain synchronous function for asynchronous code

Async projects

setTimeout()
Purpose: Executes a function after a specified delay

clearTimeout()
Purpose: Cancels a previously set timeout

setInterval()
Purpose: Repeatedly executes a function at a specified interval (in milliseconds)

Clear interval same as clear timeout

API

Fetch
Axios

Const resp = await Fetch('url') as it takes times to fetch


Data = await resp.json() to convert json we also use await as it takes time

Localstorage.getitem
Localstorage.setitem

Promise

let promise = new Promise((resolve, reject) => {


let success = true;
if (success) {
resolve('The operation was successful!');
} else {
reject('Something went wrong.');
}
});

Try catch

try {
console.log("Trying to run something...");
let result = 10 / 0;
} catch (error) {
console.log("Caught an error:", error);
} finally {
console.log("This will always run, whether an error occurs or not.");
}

Finally is optional may or may not use

You might also like