Location via proxy:   [ UP ]  
[Report a bug]   [Manage cookies]                
0% found this document useful (0 votes)
7 views

Javascript

The document discusses JavaScript basics like variables, data types, operators, conditional statements, loops, functions and arrays. It covers topics such as creating and accessing variables, type conversions, if/else statements, for/while loops, function parameters, and array methods like push, pop and length.

Uploaded by

yasorocky68
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
7 views

Javascript

The document discusses JavaScript basics like variables, data types, operators, conditional statements, loops, functions and arrays. It covers topics such as creating and accessing variables, type conversions, if/else statements, for/while loops, function parameters, and array methods like push, pop and length.

Uploaded by

yasorocky68
Copyright
© © All Rights Reserved
Available Formats
Download as TXT, PDF, TXT or read online on Scribd
You are on page 1/ 15

->Javascript basics:

use semicolon in js for better coding without errors.


___________________________________________________________________________
creating variables:
syntax: let variable name;
Ex: let var1 = 2;
console.log(var1);

output:
2
->keywords should not be used as vae=riable name.
-> digits, letters, $, _ can be used to create a variable name.
->digits tho start cheyyakudadu.
___________________________________________________________________________________
__________
->type of operator:
Syntax: typeof(variable name);

Ex:
let a = 2;
let b = 3.14;
let c = "yaso";
let d = true;
console.log(typeof(a));
console.log(typeof(b));
console.log(typeof(c));
console.log(typeof(d));

output:
number
number
string
boolean
__________________________________________________________________
->Type conversions Type casting:
Ex:
let a = 2;
let b = String(a);
let c = Boolean(a)
let d = "abc";
let e = "123"
let f = Number(d);
let g = Number(e);
console.log(b);
console.log(c);
console.log(f);
console.log(g);

output:
2
true
NaN
123
_________________________________________________________________________
->operators:
+, *, / %, etc.,

___________________________________________________________________________________
_____________________________________________
Number methods:
const num = 48; ->integer is a whole number.
const num = 48.0 -> float is a decimal point number.
const str = "48" ->it a string value.
Functions:

1. Number(variable name); -> it returns true if the value is a number or return


false if
it is not a number.

2.Number("string value"); -> it returns NaN as output.

3.Number(true); -> it returns 1 for boolean outputs.


same as for false it returns 0 as output.

4. Number.isInteger(variable name); -> checks if the number is integer or not.


for float and string vlaues it returns false otherwise true.

5. Number.parseFloat(variable name); -> it returns true for float values otherwise


flase.
and for string value containing both string value and float value together it
returns only the float vlaue and
neglects the string vlaue in it.

6. Number.parseFloat(variable name).toFixed(how many decimal values to be need for


output)); -> it returns the output of float value with
required decimal points using toFiexed() method.

7. Number.parseInt(); -> it returns the integer value and also for string and float
values it convert the value in to integer and
displays the output.

8. variable name.toString(); -> it converts the float data into a string data

9. Variable name.isNaN(); -> it checks if the number is not defined or not and for
string data it returns NaN as output.
and for only checking a string data it returns true if it is a string and for
remaining values.
___________________________________________________________________________________
______________________________________________________________

Math Methods:

1. Math.PI; -> returns pi value


2. Math.Trunc(Math.PI);-> removes the decimal values and returns a integer value
3. Math.round(value); -> it rounds up a float value to nearest number.
4. Math.ceil(value); -> it returns value rounds up the vlaue.
5. Math.floor(); -> it rounds down the value of decimal value.
6. Math.pow(base, exponent); -> it returns the square of the value.
7. Math.min(values); -> it returns the minimum value from the values we provided in
it.
8. Math.max(values); -> it returns the maximum value form the values we provided in
it.
9. Math.random(); -> it retuns a value ranging drom 0 to 1, and
to generate a random number from 1 to 10.

Ex: Math.floor(Math.round())*10+1); -> it generates a random number form 1 to 10.


if we use ceil instead of floor we have a chance to get a zero instead of getting
values from 1 to 10.
_________________________________________________________________________________

if Statements:

-> if contion is true it executes the if code in it and terminates our program
-> if we want to execute if if condition fails then we can use else statement
to execute our code for condition false.
-> we can do nesting inside a if else code for extra condition checking if
needed.

Switch statements:

-> syntax:
switch(expression or value){
case choice1:
//code
break;
case choice2:
//code;\
break;
default:
//code
}

-> for deault no break is required.


___________________________________________________________________________________
_____________

User Inputs:

->alert();
->confirm();
->prompt();
-> nullish coalescing operator returns a value defined by user if the
output has null (i.e) if we dont enter anything it dsiplays the
value we defined instead of null.
___________________________________________________________________________________
__________________

Loops:

1. while loop:
Ex:
//while loop
let var1 = 0;
while(var1 < 50){
var1 += 2;
console.log(var1);
}
//dont create a loop endlessly

2. Do- While loop:

Ex:
//do-while loop
let var1 = 0;
do
{
var1 += 1;
console.log(var1);
}while(var1<50);

3. For loop:
Ex:
for(let i=0; i<=10; i++){
console.log(i);
}

-> for(let i=0; i<=10;){


console.log(i);
i++;
}

-> let i = 1;
for(; i<=10;){
console.log(i);
i++;
}

-> for printing a name in foor loop.

Ex:
let name = "yaso";
for(let i = 0; i<= name.length; i++){
console.log(name.charAt(i));
}

->to print at a particular word in name using while loop.

Ex:
let name = "yaso";
let counter = 0;
let myletter;
while(true){
myletter = name[counter];
console.log(myletter);
if(myletter== "s"){
break;
}
counter++;
}

->method 2:
Ex:
let name = "yaso";
let counter = 0;
let myletter;
while(counter<=3){
myletter = name[counter];
console.log(myletter);
if(counter ===1){
counter += 2;
continue;
}
if(myletter === "s"){
break;
}
counter++;
}
console.log(counter);

___________________________________________________________________________________
________

Functions:

->Ex: "without parameters"

function sum(){
return 2+2;
}
console.log(sum());

->Ex: "with parameters"

function sum(n1, n2){


return n1+n2;
}
console.log(sum(2, 6));

->examples for functions:

1. function useremail(email){
return email.slice(0, email.indexOf("@"));
}
console.log(useremail("user@gmail.com"));

2. const useremail = function(email){


return email.slice(0, email.indexOf("@"));
}
console.log(useremail("user@gmail.com"));

3. Arrow function:
Ex:

const useremail = (email) => {


return email.slice(0, email.indexOf("@"));
}
console.log(useremail("user@gmail.com"));

4. uppercase for first letter only remaining will be converted to lowercase

Ex:

const uppercase = (name) => {


return name.charAt(0).toUpperCase() + name.slice(1).toLowerCase();
}
console.log(uppercase("DeCemBER"));

___________________________________________________________________________________
_________________________

//var, let, and const in javascript scope.

var a = 1;
var b = 2;
console.log(a);
console.log(b);
let x = 3;
let y = 4;
console.log(x);
console.log(y);
const c = 5;
const d = 6;
console.log(c);
console.log(d);

->Global scope:

//global scope

var x = 1;
let y = 2;
const z = 3;

// local scope
//
//local scope function
function myfunc(){
const z = 5;
console.log(y);
//local scope is nested in this function and gets the value outside the local
function the value was assigned.
{
let y = 4;
console.log(y);

myfunc();

-> //global scope

var x = 1; //function scoped


let y = 2; //block scoped
const z = 3;

console.log(`global: ${x}`);
console.log(`global: ${y}`);
console.log(`global: ${z}`);

function myfunc(){
var x= 10;
const z = 5;
console.log(`function: ${x}`);
console.log(`function: ${y}`);
console.log(`function: ${z}`);

{
var x = 11;
const z = 6;
console.log(`block: ${x}`);
console.log(`block: ${y}`);
console.log(`block: ${z}`);
}
}
myfunc();

-> var x = 1; // functional scoped


let y = 2; //block scoped
const z = 3;

console.log(`function: ${x}`);
console.log(`function: ${y}`);
console.log(`function: ${z}`);

console.log(`global: ${x}`);
console.log(`global: ${y}`);
console.log(`global: ${z}`);

function myfunc(){
var x= 10;
const z = 5;
console.log(`function: ${x}`);
console.log(`function: ${y}`);
console.log(`function: ${z}`);
{
var x = 11;
const z = 6;
console.log(`block: ${x}`);
console.log(`block: ${y}`);
console.log(`block: ${z}`);
}
}
myfunc();

-> var x = 1; // functional scoped


let y = 2; //block scoped
const z = 3;

console.log(`function: ${x}`);
console.log(`function: ${y}`);
console.log(`function: ${z}`);

console.log(`global: ${x}`);
console.log(`global: ${y}`);
console.log(`global: ${z}`);

function myfunc(){
var x= 10;
const z = 5;

{
var x = 11; //function scoped
const z = 6; //block scoped
console.log(`block: ${x}`);
console.log(`block: ${y}`);
console.log(`block: ${z}`);
}
console.log(`function: ${x}`);
console.log(`function: ${y}`);
console.log(`function: ${z}`);
}
myfunc();

___________________________________________________________________________________
__________________

-> Arrays:

-> const arr = []; => declaration of arrays.


->To add elements into the array:

Ex: const arr = [];

arr[0] = "yaso";
arr[1] = 178;
arr[2] = true;

// to print array
console.log(arr);

output: [ 'yaso', 178, true ]

-> // length of array

console.log(arr.length);

-> // last element of array

console.log(arr[arr.length - 1]);

-> //access using index

console.log(arr[1]);

->// to push data into array


arr.push("krishna");
console.log(arr);

-> // to pop data from array

last = arr.pop();
console.log(last);

-> //to add data from front in array

arr.unshift(42);
console.log(arr);

-> //to see first item data from front in the array

const firstitem = arr.shift();

console.log(firstitem);

->splice method:
Ex:

const arr = [];

arr[0] = "yaso";
arr[1] = 178;
arr[2] = true;

// to delete and add data to a particular index element in an array


arr.splice(1,1, 42);

console.log(arr);
console.log(arr[1]);

->with data assigned in array:

Ex:

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];


console.log(arr);
const newarr = arr.splice(2);

console.log(newarr);

->to reverse a array elements:

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];


arr.reverse();
console.log(arr);

-> to print letters without array format


const arr = ['a', 'b', 'c', 'd', 'e', 'f'];

const newstring = arr.join();


console.log(newstring);

output:
a,b,c,d,e,f

->split method:

Ex:

const arr = ['a', 'b', 'c', 'd', 'e', 'f'];

const newstring = arr.join();


const newarray = newstring.split(",");
console.log(newarray);

output:

[ 'a', 'b', 'c', 'd', 'e', 'f' ]

->concat method:

Ex:
const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e', 'f'];

const newarray = arr1.concat(arr2);


console.log(newarray);

output:
[ 'a', 'b', 'c', 'd', 'e', 'f' ]

->spread operator:

Ex:
const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e', 'f'];

const newarray = [...arr1, ...arr2];


console.log(newarray);

output:
[ 'a', 'b', 'c', 'd', 'e', 'f' ]

->nested array:

Ex:
const arr1 = ['a', 'b', 'c']
const arr2 = ['d', 'e', 'f'];

const newarray = [arr1, arr2];


console.log(newarray);

output:

[ [ 'a', 'b', 'c' ], [ 'd', 'e', 'f' ] ]


_______________________________________________________________________________

->document.getElementById();
->document.querySelector();
->document.getElementByClassName();
->document.getElementByTagName();
->document.querySelectorAll();
->target.textContent
->syntax: addEventListener(event, function, useCaptute)
->initApp();
->Event bubbling
->EventCapturing
->EventPropagation and StopPropogation
->useCapture: if it is true it works from outward events to inward evnents
if ir is false it works inward to outwards events in it.

___________________________________________________________________________________
___________________________________________
//Fetch API requires a discussion of...

-> callback functions:

->ex:
function firstfunction(parameters, callback){
callback();
}
//AKA "callback hell"
firstfunction(para, function(){
// do stuff
secondfunction(para, function(){
thirdfunction(para, function(){

});

});
});

-> Promises:
3 states: Pending, Fullfilled, Rejected

myPromise = new Promise((resolve, reject) => {


const error = false;
if(!error) {
resolve("yes! resolved my problem");
}else{
reject("no! rejected my promise");
}
});

console.log(myPromise);
myPromise.then(value =>{
return value + 1;
})
.then(newvalue =>{
console.log(newvalue);

})

.catch(err =>{
console.log(err);
})

const myNextPromise = new Promise((resolve, reject) => {


setTimeout(function(){
resolve("my NextPromise resolved!");
}, 4000);
});

myNextPromise.then(value =>{
console.log(value);
});

myPromise.then(value =>{
console.log(value);
});

->pending:
Ex:

const users = fetch("https://jsonplaceholder.typicode.com/users")


.then(response => {
return response.json();
})
.then(data =>{
data.forEach(user => {
console.log(user);
})
});
console.log(users);

___________________________________________________________________________________
__________________
->Await / Await:

const myusers = {
userlist : []
}

const mycoolfunction = async () => {


const response = await fetch("https://jsonplaceholder.typicode.com/users");
const jsonuserData = await response.json();
//console.log(jsonuserData);
return jsonuserData;
}

//mycoolfunction();

const anotherFunc = async () => {


const data = await mycoolfunction();
//console.log(data);
myusers.userlist = data;
console.log(myusers.userlist);
}

anotherFunc();
console.log(myusers.userlist);

___________________________________________________________________________________
________________________________

->Ex:
const getAlluserEmails = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const jsonuserData = await response.json();
const useremailarray = jsonuserData.map(user =>{
return user.email;
});
// console.log(useremailarray);
return useremailarray;
}

console.log(getAlluserEmails());

->from the above code we cant log the function but we can call the function

___________________________________________________________________________________
____

-> we can call the function like this:

Ex:
const getAlluserEmails = async () => {
const response = await fetch("https://jsonplaceholder.typicode.com/users");
const jsonuserData = await response.json();
const useremailarray = jsonuserData.map(user =>{
return user.email;
});
//console.log(useremailarray);
postToWebpage(useremailarray);
}

const postToWebpage = (data) => {


console.log(data);
}
getAlluserEmails();

output:

[
"Sincere@april.biz",
"Shanna@melissa.tv",
"Nathan@yesenia.net",
"Julianne.OConner@kory.org",
"Lucio_Hettinger@annie.ca",
"Karley_Dach@jasper.info",
"Telly.Hoeger@billy.biz",
"Sherwood@rosamond.me",
"Chaim_McDermott@dana.io",
"Rey.Padberg@karina.biz"
]

_________________________________________________________________________

->Example:

// second parameter of fetch is a object

const getdadjoke = async () => {


const response = await fetch("https://icanhazdadjoke.com/", {
method: "GET",
headers: {
Accept: "application/json"
}
});
const jsonjokeData = await response.json();

console.log(jsonjokeData);

getdadjoke();

output:

{
"id": "nbFBdiydxkb",
"joke": "Why did the barber win the race? He took a short cut.",
"status": 200
}

-> Example: to get only the data without any other attributes

const getdadjoke = async () => {


const response = await fetch("https://icanhazdadjoke.com/", {
method: "GET",
headers: {
Accept: "application/json"
}
});
const jsonjokeData = await response.json();

console.log(jsonjokeData.joke);

getdadjoke();

output:

Two silk worms had a race. They ended up in a tie.


__________________________________________________________________________-

->another way to get the joke text

Ex:

const getdadjoke = async () => {


const response = await fetch("https://icanhazdadjoke.com/", {
method: "GET",
headers: {
Accept: "text/plain"
}
});
const textjokeData = await response.text();

console.log(textjokeData);

getdadjoke();

-> output:

I was going to learn how to juggle, but I didn't have the balls.
___________________________________________________________________________________
________________________________

->Example:

// to send or post new data using the API


const jokeObject = {
id: "ucxPZDAlGlb",
joke: "If two vegans are having an argument, is it still considered beef?",
}

const postData = async (jokeObj) => {


const response = await fetch("https://httpbin.org/post", {
method: "POST",
headers: {
"Content-Type": "application/json"
},
body: JSON.stringify(jokeObj)
});
const jsonResponse = await response.json();

console.log(jsonResponse.headers);

postData(jokeObject);

-> output:

{
"Accept": "*/*",
"Accept-Encoding": "gzip, deflate, br",
"Accept-Language": "en-GB,en;q=0.9,en-US;q=0.8,hi;q=0.7,te;q=0.6",
"Content-Length": "96",
"Content-Type": "application/json",
"Host": "httpbin.org",
"Origin": "http://127.0.0.1:5500",
"Referer": "http://127.0.0.1:5500/",
"Sec-Ch-Ua": "\"Not A(Brand\";v=\"99\", \"Google
Chrome\";v=\"121\", \"Chromium\";v=\"121\"",
"Sec-Ch-Ua-Mobile": "?0",
"Sec-Ch-Ua-Platform": "\"Windows\"",
"Sec-Fetch-Dest": "empty",
"Sec-Fetch-Mode": "cors",
"Sec-Fetch-Site": "cross-site",
"User-Agent": "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36
(KHTML, like Gecko) Chrome/121.0.0.0 Safari/537.36",
"X-Amzn-Trace-Id": "Root=1-65d5cf29-44fb65071a0492c24a873083"
}

___________________________________________________________________________________
______________________________________________________________________

->

You might also like