# JS notes

## In this example below you will see how to do a JS notes with some HTML / CSS and Javascript This awesome code was written by 120hit, you can see more from this user in the personal repository.
You can find the original code on Codepen.io
• HTML
• JavaScript
``````<!DOCTYPE html>
<html lang="en" >

<meta charset="UTF-8">
<title>JS notes</title>

<body>

<script  src="js/index.js"></script>

</body>

</html>
``````
``````
var a = 1;
var b = 2;

//if (a < b){
conslole.log("in fact a is less than b")
}else{
console.log("error the first statement should be outputed")
}

//

var weather = "sunny";

if(weather === "rainy"){
console.log("the weather is rainy, bring a rain coat");
}else if(weather === "snowy"){
console.log("the weather appears to be snowy, you should bring a warm snow jacket");
}else{
console.log("the weather looks perfect for boulder! enjoy your day");
}

//

var myRoom = "cold";

if(myRoom === hot){
}else if(myRoom === cold){
console.log("wear warm socks and a jacket");
}else{
console.log("wear you normal clothes");
}

//

var number = 1232323;

if(number % 123232 === 0){
console.log("even");
}else{
console.log("odd");
}

//

var musicians = 100;

if(musicians === 1){
console.log("solo");
}else if (musicians === 2){
console.log("duet");
}else if (musicians ===3 ){
console.log("triplet");
}else if (musicians===4){
}else if(musicians > 4 ){
console.log("this is a large group");
}else{
console.log("this is not a musican");
}

//

so in java script there is a statement called if statement
if statement ties to the boolens, meaning that the if statement always has to be true or false
the first expression or else the last string of the else statement gets printed out because the
expression on the first if statement was false
if you want to add more than one statement then we do it by adding a thing called an else if statement
else if statement just means there is more content we need to add in your var and if statements

so for ex

var bike = "specialized";

if ( bike === specialized){
console.log("this is specialized mountain bike")
}else if (bike != spcialized){
console.log("this is just a regular mountain bike")
}else {
console.log("this is just a regular bike and not a mountain bike")
}

//
for this next excerise its a missing person case with the provided location and murder mystry item
we have a hand full of people we think we who the killer is in the town

var suspect = "dan";
var weapon = "";
var solved = false;

weapon = "jack stand";
solved = suspect === "dan";
}else if(location === "san juan"){
weapon = "piston";
solved = suspect === "el cuz";
}else if(location === "805"){
weapon = "guitar";
solved = suspect === "bad boys";
}else {
weapon = "base ball bat";
solved = suspect ==== "120heat";
}

if(solved){
//console.log ( `the suspect named \${dan} is hiding in the location near \${location} and we believe the weapon he used was  \${weapon}`

//////

next i will talk about logical opreators which is && and ||
the && is if it is true or false
the || is the if one of the statement is true or not

var car = "old";
var weather = "cold";

if(car === "old" && weather === "cold"){
console.log("the engine is old so the car can perform better than a hot day when the engine is stressed by the hot temputure")
}

the and oprerator combines two logical expression together into a larger logical expression
the rules of the && expression is if both of the expression is true then it will execute
if only one of the expression is true then the whole expression becomes false

there are three logical operators
&&
||
!

next is the || this is the or operator ,
the rules for this is if even one of the expression is true then the program will execute
or if both expression is true it will again will execute because both the expresion are valid with the program

next is the !, this just means do not equal to so ex is 11 != 12 //true

ok we are back again with the flow of the code

if(x > y && y > x){
console.log("so which is greater")
}

//

var balance = 100;
var checkBalance = true;
var isActive = false;

if(checkBalance){
if(isAcive && balance > 0){
}else if(!isActive){
}else if(balance === 0){
}else{
}else {
console.log("Thank You and have a nice day");
}

//the bottom example wont work but just playing with the code that is all

var icecream = {
flavors : ["choc", "vnilla", "cheesecake"],
vessel: ["cone", "cup"],
topping: ["sprinkles", "eniemem"],

makeIcecream: function(){
if(
(flavor === "choc" || flavor === "vnilla") &&
(vessel === 'cone' || 'cup') &&
(topping === "sprinkles" || topping === 'eniemem')
)
{console.log( `i want 2 scopes of \${flavor}, with \${topping} and on a \${vessel} `)}
}

makeIcecream();
}

//this is the correct way to apply the code for this icecream example

var flavors = "choc";
var vessel = 'cone';
var toppings = 'coconut';

if(
(flavor === 'choc' || flavor === 'vnilla') &&
(vessel === ' cone' || vessel === 'cup') &&
(topping === 'coconut' || topping === 'eniemem'){
//console.log ( `i want 2 scopes of \${flavor} with \${topping} and in a \${cone}`)
};
)

//

/*in this next example we using the
if statement
the &&
the ||
< or > */

var shirtWidth = 1;
var shirtLength = 1;
var shirtSleeve = 1;

if(shirtWidth >= 1.0 && shirtWidth <2.0 &&
shirtLength >= 2.

)

there are 6 falsy values in js

- if the boolean is false
-if the code is undefined
-if the value is 0
-if the value is an empty string ""
-if the value is not a number like NAN
-if the value is null

//

ternary operators

sometimes when there is a truthy like a boolean being true and a var with no value, it turns in to a ternary

ranther than assinging a variabe to become true

ex
var isGoing = true;
or
(isGoing === true)
or
(isGoing === false)

we can just say

ex
if(isGoing) , the value inside the curly brackets, js automatically assumes it is a true value

if you want the value to become false then you can type
ex

if(!isGoing)

the ! in the value makes the value automatically a false

ternary operators adds a shortcut element to the code and makes lengthy if statement code less lenghty

//lenghthy code
var isGoing = true;
var color;

if (isGoing) {
color = "green";
} else {
color = "red";
}

console.log(color);

//less lengthy code
var isGoing = true;

var color = isGoing ? "blue" : "red";
console.log(color);

to properly use the ternary operator you need  to make it so

[conditional ? the true value : the false value]

-
write the conditional on the left side of the ? and on the right side of the ? write your code if your condintions is true and the true condition is seperated by the collen : the right side of the collen is the false condintion

-
the [code below] is the [cleaner code],
ok if we [discect] the [code] like [earlier]
i talked about the [isGoing] is [automatically] [true]
and [!isGoing] is [false]

the [value] [inside] [color] is [isGoing] and is [automatically] a [true] [value] the [string] called [blue] will be the [output]

if i added the ! in the isGoing like this var color = !isGoing , then the out put will be [red] because isGoing is now a false conditional
-

var isGoing = true;

var color = isGoing ? "blue" : "red";
console.log(color);

//

[conditional ? the true value : the false value]

//

var eatsAnimals = true;
var eatsPlants = true;

var category = (eatsAnimals && eatsPlants) ? "omnivore" : (eatAnimals) ? "carnivore" : (eatsPlants) ? "herbivore" : unfined;
console.log(category);

//switch aexample

var troll = prompt("You're walking through the forest, minding your own business, and you run into a troll! Do you FIGHT him, PAY him, or RUN?").toUpperCase();

switch(troll) {
case 'FIGHT':
var strong = prompt("How courageous! Are you strong (YES or NO)?").toUpperCase();
var smart = prompt("Are you smart?").toUpperCase();
if(strong === 'YES' || smart === 'YES') {
console.log("You only need one of the two! You beat the troll--nice work!");
} else {
console.log("You're not strong OR smart? Well, if you were smarter, you probably wouldn't have tried to fight a troll. You lose!");
}
break;
case 'PAY':
var money = prompt("All right, we'll pay the troll. Do you have any money (YES or NO)?").toUpperCase();
var dollars = prompt("Is your money in Troll Dollars?").toUpperCase();
if(money === 'YES' && dollars === 'YES') {
console.log("Great! You pay the troll and continue on your merry way.");
} else {
console.log("Dang! This troll only takes Troll Dollars. You get whomped!");
}
break;
case 'RUN':
var fast = prompt("Let's book it! Are you fast (YES or NO)?").toUpperCase();
if(fast === 'YES' || headStart === 'YES') {
console.log("You got away--barely! You live to stroll through the forest another day.");
} else {
console.log("You're not fast and you didn't get a head start? You never had a chance! The troll eats you.");
}
break;
default:
console.log("I didn't understand your choice. Hit Run and try again, this time picking FIGHT, PAY, or RUN!");
}

//udacity example
switch (option) {
case 1:
console.log("You selected option 1.");
case 2:
console.log("You selected option 2.");
case 3:
console.log("You selected option 3.");
case 4:
console.log("You selected option 4.");
case 5:
console.log("You selected option 5.");
case 6:
console.log("You selected option 6.");
}

//

switch(meditation){
case 'where':
console.log("my room");
case 'why':
console.log("self");
case 'when':
console.log("around 11:00 am");
}
//

var x = 1;

while(x <= 100){
console.log(x + " mississippi");
x += 1;
}

//

var x = 1;

while(x < = 20){
if(x % 3 === 0 && x  % 5 === 0){
console.log("RohitShrestha");
}else if(x % 3 === 0){
console.log("Rohit");
}else if(x % 5 === 0 ){
console.log("Shrestha");
}else{console.log(x);}
x = x + 1;
}

//

var x = 1;

while(x <= 20)
{
if(x % 3 === 0 && x % 5 === 0)
{console.log('JuliaJames');}
else if(x % 3 === 0)
{console.log("Julia");}
else if(x % 5 === 0 )
{console.log("James");}
else{console.log(x);}
x = x + 1;
}

//

var age = 60;

while(age > = 0){
var prefix = "At age " + age;
var countdown = "";
var message = "";
countdown = message = age === 50 ? 'rohit is offically old now' :
time === 40 ? 'rohit is married and with a kids':
time === 30 ? 'rohit should consider now to have kids':
time === 23 ? 'rohit is slowly learning self and how the human mind and body works': prefix;
console.log(countdown);
time --;
}

//
var time = 60;
while(time >=0){
var prefix = 'T-' + time + ' seconds';
var message = "";
var countDown = "";
countDown = message = time === 50 ? 'Orbiter transfers from ground to internal power':
time === 31 ? 'Ground launch sequencer is go for auto sequence start' :
time === 16 ? 'Activate launch pad sound suppression system' :
time === 10 ? 'Activate main engine hydrogen burnoff system' :
time === 6 ? 'Main engine start' :
time === 0 ? 'Solid rocket booster ignition and liftoff!' : prefix;
console.log(countDown);
time --;
}

//

var time  = 60;

while(time >= 0){

var prefix = "In " + time + " mins";
var message = "";
var countDown = "";
countDown = message = time === 59 ? "You journey starts" :
time === 50 ? "you will meditate for 20 mins focusing in the seven chakaras and your breath" :
time === 30 ? "then for another 10 mins you will focus on what matters to you ":
time === 10 ? " after the meditation you will go to youtube and listen to alpha sounds" : prefix;
console.log(countDown);
time --;
}

//
the for loop.

the for loop has all the conditionals in its loop
the conditionals are start, stop, and armethtic like add or subtract;
for the start condintional you have to start with var i = 0;
then we decide when to stop looping the code
ans finally for the third conditional we loop with the desired armethtic

an example of an for loop

for(var i = 0; i < 10; i++){ //i = i + 1 or i++ its the same thing
console.log("printing out i = " + i )
}

//nested for loop

so a nested for loop is a for loop inside another for loop

for example

for(var x = 0; x <= 3; x++){
for (var y = 0; y <= 2; y++){
console.log(x + "," + y)
}
}

when the loop starts the first output is 0,0
then the for loop y that is nested in the parent loop always starts and executes untill its done looping completely
so for example it would look like this

0,0
0,1
0,2

after the y is done looping the x starts to loop to
1,0
1,1
1,2

2,0
2,1
2,2

3,0
3,1
3,2

//increment and drecerment
for ( var x = 0; x <= 2; ++x){
console.log(x);
}

so there is a thing in js that has x++ and ++x
the difference is that x++ outputs the original output and then it outputs the x++ increment
but for the ++x the output is instant and does not display the original output and instanly output the ++x logic
for exmple

var x = 0;
x++;

//0
//1

var x = 0;
++x;
//1

udacity says it matters on what program you use and how you implement it in the end

//quiz

for this quiz i have do a facrorial of 12 using for loop and multiple it by x.

var solution = 1;
for(x = 1 ; x <=12; ++x){
solution *= x;
}
console.log(solution)

//quiz

for(x = 0; x <= 26; ++x){
for(y = 0; y <= 99; ++y){
console.log(`\${x} - \${y}`)
}
}

//function--------------------------------------------------

in this function we will convert a string to a reverse string

function reverseString ( reverseMe){
var reverse = "";
for(var i = reverseMe.length -1; i >= 0; i--){
reverse += reverseMe[i];
}
return reverse;
}
console.log(reverseString("hi"))

//-----------------------------------------------------------

function reverseDay (reverseMorning){
var reverseM = "";
for(var i = reverseMorning.length -1; i  >= 0; --i){
reverseM += reverseMorning[i];
}
return reverseM;
}

console.log(reverseDay("day"));

//

function findAverage (x,y){
var answer = (x+y) / 2;
}

////////////////////////////////////////
console.log(findAverage(10,20));
///////////////////////////////////////////////
they yield the same answer in the end

//
function reverseString (reverseMe){
var reverseM = "";
for(var i = reverseMe.length -1; i >= 0; i--){
reverseM += reverseMe[i];
}
return reverseM;
}

console.log(reverseString"kayak")

function multiply(x){
return x * x;
}

function squared(x){
return (multiply(x) + 2);
}

console.log(squared(2));

//

function square(x) {
return x * x;
}

function subtractFour(x) {
return square(x) - 4;
}

console.log(subtractFour(5))

//

the return is the print input

//
Using Return Values
Returning a value from a function is great, but what's the use of a return value if you're not going to use the value to do something?

A [function]'s [return value] can be [stored] in a [variable] or [reused] [throughout your program] as a [function argument] . Here, we have a function that adds two numbers together, and another function that divides a number by 2. We can find the average of 5 and 7 by using the add() function to add a pair of numbers together, and then by passing the sum of the two numbers add(5, 7) into the function divideByTwo() as an argument.

And finally, we can even store the final answer in a variable called average and use the variable to perform even more calculations in more places!

// returns the sum of two numbers
return x + y;
}

// returns the value of a number divided by 2
function divideByTwo(num) {
return num / 2;
}

var sum = add(5, 7); // call the "add" function and store the returned value in the "sum" variable
var average = divideByTwo(sum); // call the "divideByTwo" function and store the returned value in the "average" variable

//
function fullName(R, S){
return R + S ;
}

var PersonsName = fullName("Rohit ", "Shrestha");

function evolving(){
var add = PersonsName + " is evolving, and your doing great";
}

var self = evolving();

//////////////////////////////////////////////////////////

return x+ y ;

}

function divideBYTwo(num){
return num / 2;
}

var avg = divideByTwo(sum)

//

so we have two functions with two different math techniques in them one function adds and the other function divides them
then we have two variables that interwine which each other to create our results

for the add function , we first create a function called add, and has 2 parameters called x and y
then inside the add function we have a return value with the add functionality of x and y , x + y

for the divide function we haave the function name set to divideByTwo with the parameter called num
inside the divide function we have a return of the parameter num and / 2

finally the first variable is called sum, the var name doesnt really matter, it just has to make sense in the contex of the function. So we have the name of the var called sum and with the equal of the add function name [add] and insde the smooth brakets we have two test numbers in out case we have 2 and 3.

for the second and last varibale we have the variable called avgerage which equals the name of the second function callled
[divideByTwo] and next to it is the var called sum we used earlier so i guess naming the var does matter because like i said earlier the two variables interwine with each other.

so now all the functon of add has been added to the var called sum &
with the var avg we can store and switch the parameter of the second function called num and replace it with the var sum
so now

the function divide can return the added sum values of the test numbers and divide it by 2.

//

scope

the concept of scope is that there are two different kinds of scope

there are gobal scope and function scope

- Gobal scope identifires can access the scope anywhere from the program
-function scope is only limted within your function and your function only

an example would be the variable

if the var is outside of the function then the var is considered as the gobal scope

//

var rohit= "what is the concept of enlightment";

function vidas(){
var guru = "it is within self, only the soul can achieve enlightment, meditatation is the key";
function englightment (){
var student = "thank you guru, i will meditate "
}
}

//

like scope, shadowing is if the gobal var say var x has the same name as the var name inside the function but without the "var" then the function will take over the name x and override it.and if we say console.log(x) then the function x will print out and not the gobal var x. the solution for this is inside the function rather than just saying x = "y" we need to add a "var" in front of the x = "y" so js doesnt missunderstood it. now even though the gobal var name and function var name is the same, both of the values will be printed.

so here is example of the overide, the function overrided the var booktile to its own booktitle
////////////////////////////////////////////////////////////////////////////////////////////////////
var bookTitle = "hachet";
console.log(bookTitle);

function showBookTitle(){
bookTitle = "MaximumRide";
console.log(bookTitle);
}

showBookTitle();
console.log(bookTitle);

//hachet
//MaximumRide
//MaximumRide
//////////////////////////////////////////////////////////////////////////////////////////////
in this example below we added a var in front of the booktitle inside the function callled showBookTitle
so now it will print out gobal var called booktitle first
then it will print out the function called showBooktitle, also in a function you always has to call it,
and finally because we commanded that we console.logged booktitle
the boooktitle called hachet will print out agian in the  console

var bookTitle = "hachet";
console.log(bookTitle);

function showBookTitle(){
var bookTitle = "MaximumRide";
console.log(bookTitle);
}
showBookTitle();

console.log(bookTitle);

//hachet
//MaxumumRide
//hachet

//

SCOPE RECAP

so when an indentifer is declared in a gobal scope, it is available everywhere

if the indentifer is declared in the function scope then it is available in the function it was declared in

when the [javascript engine] is [tring to declare an indentifer] it will always [look first] in the [current function] and [if the js engine] [doesnt find it] then it [look] for it in the [next function] and [so forth untill] there are [no more funcitons] to [look for] and then [finally] it will [look in the gobal scope]

//Hoisting

in js there is a quirk called hoist

function hoist

hosting in js will hoist any function to the top of the program. even if we have the call back feature of a function on top of the actual function, js will hoist the function to the top even though the code still looks like the call function code is on the top of the actual function. The results doesnt get effected but the core code rules are we intrpurt and read code top to bottom, thats how code works, but i guess hoist overrides thsese core rules.

variable hoist

like how the function will get hoisted to the top of the script, variables will also get hoisted to the top of the function, so usually js programmers will just declare the variable and assign a value to the top of the function, so we dont need to deal with the error in the first place.

//function expression

function expression is a variable that has a function inside it and now naming the function is redundent and so now the function is anonymous funcion because the parent var has the name now

so function expression is storing a function inside a vaiable.

if you need to call the function just call the name of the vaiable with (); in it and it will work.
//////////////////////////////////////
var hi = function(x){
var greeting = "HI";
greeting += x;
}
return greeting;

hi();

//

var sayHi = function(){
return "Hi";
}

//sayHi();
//"Hi"

//arrays

arrays allows us to go through the elements by using a index of 0 > how many array elements are there.

we can also use for loop to add stuff like the upper case feature or if we want to add like a another string attached to the indexes or the array we can do that and so on.

var soccerBalls = [
["nike - red", "nike - white" , "nike - blue"],
];

soccerBalls[0,1 , 2]
////////////////////
//aex

for this next example we will use 3 methods
these methods are

var with array
and new array method called forEach method

//////////////////////////////////////////

var donuts = ["glazed", "basic",];

function donutFunctionality(donut){
donut += " donut";
donut = donut.toUpperCase;
console.log(donut);
}

donuts.forEach(donutFunctionality);

//

in the above example we disscussed about what kind of methods we needed to execute this code
now lets dive in more in detail

in the var donuts array we have two index elements and they are glazed and basic

next in the function we have a function called donutFunctionality with the parameter called donut
with this parameter we added functionality like adding a extended string " donut"
so donut += " donut" means that our parameter will add the string in the main donut variable array right in the index elements of all the elements inside the array so now it should print ex for
index 0 it should now be printed glazed donut vs before the functionality glazed
next is the feature to uppercase the elements, this code requires the .toUpperCase method, which will upper case the strings in the element array
and finally in the function we have to console.log(parameter) which is donut

the final method is a new array method called forEach
so forEach method allows us to be more preciese on where exactly we are executing the feature,
the above example we did var.forEach(function name) ,
this style of code works if you want to use the function else where as well
but the forEach can be added as a inline block code in with the function if we just using the function once

//

var donuts = ["glazed", "basic",];

donuts.forEach(
function donutFunctionality(donut)
{  donut += " donut";
donut = donut.toUpperCase;
console.log(donut);
}
);

//

so now the new code has a inline block code for the forEach

now var.forEach consumes the whole function inside its parameters

again use the inline forEach feature only if the function is only used once, which is funny cuz functions are made so we can use it multiple times wiht other meathods and code
but the once for the foraEach makes the code neat and cleaner

in the future we will use objects to store in all functions, vars, arrays all inside objects
with a simplier style of code techniques

objects are similiar to arrays where arrays uses [], objects uses {} to store in all its code

//array quiz

you will be provided with an array on numbers

var exampleNumbers = [1,2,3,4,5,6,7,8,9,10];

next you will need to use the forEach and an function and find out if the array numbers above is divisible by 3 and if so then add 100 to the desineted divisble number

//

var exampleNumbers = [1,2,3,4,5,6,7,8,9,10];

exampleNumbers.forEach(
if(num % 3 === 0)
{  array[index] = num += 100;}
console.log(exampleNumbers)
}
);

--------------------------------------------------------

function sayHi(name){
var greeting = "hello" + name;
console.log(greeting);
}

sayHi("Rohit");
-----------------------------------------------------
function sayBye(dude){
var bye = `peace out \${dude} I'll see you next time`;
return bye;
}

sayBye("Susan");

---------------------------------
var sum = x + y;
return sum;
}

-----------------------------------

var sum = x + y;
return sum;
}

-------------------------------------
function driverAge(age){
if(age >= 16){
return true;
}
return false;
}
--------

var youngMe = 15;
var canIDrive = driverAge(youngMe);
console.log(canIDrive);

var currentMe = 22;
var iCanDrive = driverAge(currentMe);
console.log(iCanDrive);

driverAge(22);
``````
{"ft_lang_label":"__label__en","ft_lang_prob":0.73510015,"math_prob":0.9701587,"size":25772,"snap":"2020-45-2020-50","text_gpt3_token_len":6600,"char_repetition_ratio":0.18235797,"word_repetition_ratio":0.05215213,"special_character_ratio":0.31196648,"punctuation_ratio":0.12906589,"nsfw_num_words":0,"has_unicode_error":false,"math_prob_llama3":0.95369667,"pos_list":[0,1,2],"im_url_duplicate_count":[null,2,null],"WARC_HEADER":"{\"WARC-Type\":\"response\",\"WARC-Date\":\"2020-10-28T02:37:08Z\",\"WARC-Record-ID\":\"<urn:uuid:e6c64c6d-0869-45f8-ae49-cd9390318be0>\",\"Content-Length\":\"125365\",\"Content-Type\":\"application/http; msgtype=response\",\"WARC-Warcinfo-ID\":\"<urn:uuid:be25c7dd-5d1a-4a61-9ec7-17f22392d9eb>\",\"WARC-Concurrent-To\":\"<urn:uuid:667e403c-e890-4138-8941-82044bbb63fb>\",\"WARC-IP-Address\":\"157.230.75.163\",\"WARC-Target-URI\":\"https://www.codeseek.co/120hit/js-notes-GMNQro\",\"WARC-Payload-Digest\":\"sha1:JWJ3Z7FNHWZAZIPPZTUNEYL4RT6C2VSX\",\"WARC-Block-Digest\":\"sha1:M75GSTQYNISC2R24XHTUNU6QC5RZF4GA\",\"WARC-Identified-Payload-Type\":\"text/html\",\"warc_filename\":\"/cc_download/warc_2020/CC-MAIN-2020-45/CC-MAIN-2020-45_segments_1603107896048.53_warc_CC-MAIN-20201028014458-20201028044458-00524.warc.gz\"}"}