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

Remember: Order of Tag Script: // Always at The Beginning of The Code. No Later of Some Code Because Won T Work This

The document provides an overview of JavaScript concepts including: 1) How to define variables using var, let, and const and the differences between them. It also covers variable scope and redeclaration. 2) JavaScript data types including arrays, objects, and methods to manipulate them. 3) Control flow structures like if/else statements, loops (for, for-in, for-of, while, do-while), and switch statements. 4) Operators for comparisons, logic, and assignments. 5) Functions and how to use return values.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
0% found this document useful (0 votes)
83 views

Remember: Order of Tag Script: // Always at The Beginning of The Code. No Later of Some Code Because Won T Work This

The document provides an overview of JavaScript concepts including: 1) How to define variables using var, let, and const and the differences between them. It also covers variable scope and redeclaration. 2) JavaScript data types including arrays, objects, and methods to manipulate them. 3) Control flow structures like if/else statements, loops (for, for-in, for-of, while, do-while), and switch statements. 4) Operators for comparisons, logic, and assignments. 5) Functions and how to use return values.
Copyright
© © All Rights Reserved
Available Formats
Download as DOCX, PDF, TXT or read online on Scribd
You are on page 1/ 26

Remember: Order of Tag Script

Maybe you could experiment issues when you put the script tag before the HTML element
you want to edit.

Use of Strict Mode


'use strict'; // Always at the beginning of the code. No later of some code because won´t work this
Help us to find hidden issues

Change HTML/CSS
onclick=”document.getElementById(‘demo’).innerHTML=’Some Text’” // Change HTML values
onclick=”document.getElementById(‘demo’).style.fontSize=’34px’” // Change Styles CSS

Defining Pro-Variables
var a,b,c;
a = 4;
b = 5;

var a = 4,
b = 5,
c = 6;

Let, Const and Var


var i = 5;
for (var i = 0; i < 10; i++) {
// some statements
}
// Here i is 10

Note: A for loop redeclare a variable at same time than conditionals for a var

let i = 5;
for (let i = 0; i < 10; i++) {
// some statements
}
// Here i is 5

“Let doesn´t change the value of the variable outside of brackets fortunately (redeclare). You
can continue in order” “i it´s only 10 inside the for loop”
Redeclare a var with let is impossible.

Redeclaring a let variable with let, in the same scope, or in the same block, is not allowed.
Instead, redeclaring a variable with let, in another scope, or in another block, is allowed.

On the other hand, variables defined with const behave like let variables, except they
cannot be reassigned.

JavaScript const variables must be assigned a value when they are declared.

// This is incorrect
const PI;
PI = 3.14159265359;

// This is correct
const PI = 3.14159265359;

Const variable must be unique for it. Can´t be a redeclared variable name.

Comparisons
== Equal to //5=5, 5=”5”
=== Equal value and equal type
!= not Equal
!== not Equal value or not equal type
> Greater than
< Less than
>= Greater than or equal to
<= Less than or equal to

Logical Operators
&& and
|| or
! not

Objects
var car = {type:"Fiat", model:"500", color:"white"};

An object has properties and methods:


● car.name = “Fiat”; //Is a property (Fiat is the value)
● car.drive(); //Is a method resulted of a function

To access to the values of the properties, only use this formula:


objectName.propertyName;
To access to the methods, only use this formula:
objectName.methodName();

Delete Keyword
delete deal3.market;

propertyExists = "market" in deal3; // Check if the property market exist in the object deal3

Arrays
var cars = ["Saab", "Volvo", "BMW"];
cars[0]; (First Value)
var last = fruits[fruits.length - 1]; (Last Value)

Arrays are a special type of objects.


> In JavaScript, arrays use numbered indexes.
> In JavaScript, objects use named indexes.

You should use objects when you want the element names to be strings (text).
You should use arrays when you want the element names to be numbers.

Methods
● toString() // Converts an array to a string of (comma separated) array values.
● join(“*”) // It behaves just like toString(), but in addition you can specify the separator. Use with map()
● pop() // Removes the last element from an array
● push(“val”) // Adds a new element to an array (at the end)
● shift() // Removes the first array element and "shifts" all other elements to a lower index.
● unshift(“val”) // Adds a new element to an array (at the beginning), and "unshifts" older elements.
● slice(2, 0, “Lemon”, “Kiwi”) // Used to add new items to an array or test something
● splice(i, 2) // Very similar to slice the unique difference is which this delete array elements
The first parameter (2) defines the position where new elements should be added (spliced
in).

The second parameter (0) defines how many elements should be removed.

The rest of the parameters ("Lemon" , "Kiwi") define the new elements to be added.

● var.concat(var2,var3) // Creates a new array by merging (concatenating) existing arrays


● slice(1,3) // Slices out a piece of an array into a new array

Array Sort
● sort() // Sorts an array alphabetically
● reverse() // Reverses the elements in an array.
● function(a, b){return a - b} // Comparing function
● Math.max.apply to find the highest number in an array
function myArrayMax(arr) {
return Math.max.apply(null, arr);
}

Arr Iteration** [Loops]


● .forEach(function) // Calls a function (a callback function) once for each array element
● .map(function) // Creates a new array by performing a function on each array element. No need index, length, incrementor
● .filter(function) // Creates a new array with array elements that passes a test
● .reduce(function) //

Loops

Loop for
if you want to run the same code over and over again, each time with a different value.
Counter, i (iteration), serves two purposes. It keeps track of the number of iterations so
looping can halt at the right point. And it serves as the index number of the array, allowing
the code to progress through all the elements of the array as the counter increments with
each iteration.

var cars = ["BMW", "Cadillac", "Mercedez", "Ford"];


var text = "";
for (i = 0; i < cars.length; i++) {
text += cars[i] + "<br>";
}

Note: You must call the var text if you want to write a text with the elements of array.

var matchFound = false;


for (var i = 0; i <= cleanestCities.length; i++) {
if (cityToCheck === cleanestCities[i]) {
matchFound = true;
alert("It's one of the cleanest cities");
break; // Avoid repeat the code 4 times if it finds a solution
}
}
if (matchFound === false) {
alert("It's not on the list");
}

Note: Use matchfound to define a code when the loop leaves an undefined value.
Loop for in
Loops through the properties of an Object.

var numbers = [45, 4, 9, 16, 25];

var txt = "";


var x;
for (x in numbers) {
txt += numbers[x] + "<br>";
}

Loop for of
let text = "";

for (let x of cars) {


text += x + "<br>";
}

While Loop
var text = "";
var i = 0;
while (i < 10) {
text += "<br>The number is " + i;
i++;
}

Note: While loops are more versatile because you only need a condition.

const roll = document.getElementById('roll');


roll.addEventListener('click', () => {
let dice = Math.trunc(Math.random() * 6) + 1;

while(dice!==6){
console.log(`You rolled a ${dice}`);
dice = Math.trunc(Math.random() * 6) + 1;
if (dice === 6) {
console.log('You win');
}
}

})
Do While Loop
var text = ""
var i = 0;

do {
text += "<br>The number is " + i;
i++;
} while (i < 10);

● Instead of while, the keyword does lead off the statement.


● The while clause, including the loop-limiting code inside the parentheses, moves to
the bottom—after the closing curly bracket.+
● Code between “do” semicolons is executed one time no matter if the condition isn´t
true

Break and Continue Statements


The break statement "jumps out" of a loop.
The continue statement "jumps over" one iteration in the loop.

var text = "";


var i;
for (i = 0; i < 10; i++) {
if (i === 3) { break; }
text += "The number is " + i + "<br>";
}

Conditions

If
if (condition){
// block to be executed if condition is true
} else{
// block to be executed if condition is false
}

Else If
if (condition1) {
// block of code to be executed if condition1 is true
} else if (condition2) {
// block of code to be executed if the condition1 is false and condition2 is true
} else {
// block of code to be executed if the condition1 is false and condition2 is false
}

Ternary Operator
variablename == (condition) ? value1:value2

function myFunction() {
var age, voteable;
age = document.getElementById("age").value;
voteable = (age < 18) ? "Too young":"Old enough";
document.getElementById("demo").innerHTML = voteable + " to vote.";
}

Note: We can assign the ternary operator to a variable. Use it as an expression

Switch
switch(expression) {
case x:
// code block
break;
case y:
// code block
break;
default:
// code block
}
switch (new Date().getDay()) {
case 0:
day = "Sunday";
break;
case 1:
day = "Monday";
break;
case 2:
day = "Tuesday";
break;
case 3:
day = "Wednesday";
break;
case 4:
day = "Thursday";
break;
case 5:
day = "Friday";
break;
case 6:
day = "Saturday";
default:
day = "Saturday";
}
Note: Keyword case is the same as saying “===”. e.g., case 0 → var switched === 0

function gradeCalculator(grade) {
switch (true) {
case (grade >= 90):
return "A"
case grade >= 80:
return "B"
case grade >= 70:
return "C"
case grade >= 60:
return "D"
case grade <= 59:
return "F"
}
}

Scope - Global and Local Variables


Is a global variable when is defined along the code; Is a local variable when is defined inside
a function

> A global variable can be displayed in anything element like an object, array, or function
> A local variable only can be used in the function in which was declared

Note: Using more local than global variables is better for speed and cleanliness.

Return Keyword
Use the return keyword inside a function when you want to return the parameters contained
in a variable, that is to say, when you don't call the function directly otherwise through a
variable. As an example, when you make an operation inside a variable, you must return the
variable. Return the code value without matter the scope

What you put next the return keyword is what will be returned as a value. To use this value
returned we must save the invoking function into a variable.

let fruitsProccesor = (apples, oranges) => {


console.log(apples, oranges);
const juice = `Juice with ${apples} apples and ${oranges} oranges.`;
return juice; // Return the const as a string value
};

const appleJuice = fruitsProccesor(5, 4);

console.log(appleJuice); // This will be Juice with ...


Functions
Function arguments are listed inside the parentheses () in the function definition. [Calling Function]

Function parameters are the values received by the function when it is invoked.

Inside the function, the arguments (the parameters) behave as local variables.

Pro Function (Arrow)


const hello = (arguments) => {
// Code to execute
}
hello (parameters);

Note: If you have a single line of code, you don't need to use the return keyword, in case
you were going to use it.

const sum = (a, b) => a + b // By default result is returned. This no apply for arrow´s function values enclosed in braces

Function Use I (use it with loops)


function sumAll(arguments) {
var i;
var sum = 0;
for(i = 0; i < arguments.length; i++) {
sum += arguments[i];
}
return sum;
}
document.getElementById("demo").innerHTML = sumAll(1, 123, 500, 115, 44, 88);

Function Use II (use more arguments)


function greetUser(greeting) {
alert(greeting);
}

The name of the function and the name of the parameter don't have to have anything in
common.

function calcTot(merchTot) {
var orderTot;
if (merchTot >= 100) {
orderTot = merchTot;
}
else if (merchTot < 50.01) {
orderTot = merchTot + 5;
}
else {
orderTot = merchTot + 5 + (.03 * (merchTot - 50));
}
return orderTot;
}

Note: Use this to calculate taxes, costs, sums, substractions, divider, multiplier, etc.

Apply, Call and Bind Methods


func.apply(thisArg, [ argsArray])

func.call([thisArg[, arg1, arg2, ...argN]])

Callbacks
Use callbacks to actualize a function and take advantage of the scope.

function sum(a, b, cb) {


const op = a + b; // Remember you can´t use this value unless you return it. In this case you want to use it as a variable avoiding the scope
cb(op); // Here you use a value inside a function that you cannot use outside from it, but in this case with a callback you can use it immediately in another function
}

const callback = (operation) => {


console.log("Result", operation); // Here you use the value of op from the sum function because you use this function as a parameter in the function call
}

sum(4, 5, callback); // Here you use the parameter you´ll use in the first function, next is the parameter of the callback

///
const english = [
{learn: "Wonderful", translate: "Maravilloso"},
{learn: "Magnify", translate: "Aumentar"},
{learn: "Till", translate: "Hasta"}
];

let getVocabulary = () => {


let output = "";
english.forEach((word, index) => {
output += "<li>" + word.learn + "</li>";
});

document.body.innerHTML = output;
}
let newVocabulary = (newWord, callback) => {
english.push(newWord);
callback();
}

newVocabulary({learn: "Hello", translate: "Hola"}, getVocabulary);

Note: You can do the callback without the need of using the callback function as a
parameter. You can simply put the function inside the other function and will work.

Note: Use it to actualize the post-data in arrays for example.

Key: Different function

Recursion
It's when you call the same function inside it. It´s used to create functional loops, and to
render the same function for specific reasons like actualizing the indexes.

const render = () => {


todo.value = "";
const todoList = document.getElementById("todo-list");

const todosTemplate = todos.map(t => "<li>" + t + "</li>");


todoList.innerHTML = todosTemplate.join("");

const elements = document.querySelectorAll("#todo-list li");

elements.forEach((element, i) => {
element.addEventListener("click", () => {
element.parentNode.removeChild(element);
todos.splice(i, 1);
actualizeTodos(todos);
render(); // This actualizes the index because the function is recharged.
})
})
}

Note: Recursion is ideal to render the program. Use it to actualize indexes for example.

Key: Same function

Spread Operator
We use it when we want to create an exact copy of an object, but if we modify this copy that
doesn't alter the original.

/* The Problem */
const a = {x: 1};
const b = a;

b.y = 2; // In this case you assign the same propertie y to a

a.z = 3; // Same for this. Here you assign propertie z to b

a === b; // True

/* The Solution*/
const c = {...a}; // c is the new a

a === c // False

Promises
A promise is a value that will be resolved in the future.
Promise.resolve(2)
.then(val => val + 1)
.then(val => console.log(val))
.catch(e => console.error(e))

Promise.reject(2)
.then(val => val + 1)
.then(val => console.log(val))
.catch(e => console.error(e))

● then is the code to execute


● catch is like an else in a conditional. Works to manage issues
● resolve is to resolve something
● reject is to make fail the promise

Closures
Function returned inside another function. The advantage is which you can create local
useful variables before the returning statement.

Secret
Functions are VALUES, the proposal of making a function is to return something that is
value.

Constructors
function Plan(name, price, space, transfer, pages) {
this.name = name;
this.price = price;
this.space = space;
this.transfer = transfer;
this.pages = pages;
}

var plan1 = new Plan("Basic", 3.99, 100, 1000, 10);

Prototype
Prototypes are used to call a method inside a constructor one time for each new object we
want to create. When we use a constructor, the method is repeated again and again when
you use the constructor. To create a shared method for all the elements, is the prototype.
You should have in mind when you create a new object you only can assign the properties,
to call the method you must call it outside.

Plan.prototype.calcAnnual = function(percentIfDisc) {
var bestPrice = this.price;
var currDate = new Date();
var thisMo = currDate.getMonth();
for (var i = 0; i < this.discountMonths.length; i++) {
if (this.discountMonths[i] === thisMo) {
bestPrice = this.price * percentIfDisc;
break;
}
}
return bestPrice * 12;
};

String Methods
● indexOf(“text”, <<number>>); //returns the position of the first occurrence of a specified text.
● includes(‘str’); // same than indexOf, the difference is this return a boolean, besides you can check nums
● lastIndexOf(“text”); //returns the position of the last occurrence of a specified text.
● search(“text”); //same than indexOf. However this last cannot use advanced parameters

● slice(start, end); //extracts a part of a string and returns the extracted part in a new string.
● substring(start, end); //similar to slice. However this cannot accept negative parameters.
● substr(start, length); //similar to slice. The difference is that the second parameter specifies the
length of the extracted part.
● var newText = text.replace(/World War II/g, "the Second World War"); //Global variable
replace

● replace(“text”, “newText”); //replaces a specified value with another value in a string


function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/Microsoft/g,"W3Schools");
document.getElementById("demo").innerHTML = txt;
}

● text1.concat(“”, “text2”); //Joins two or more strings


● str.trim(); //Erase white space in a string

● str.charAt(#); //Returns the character at a specified index (position) in a string.


● charCodeAt(); //Returns the unicode of the character at a specified index in a string.

● str.split(“,”); //String to an Array

Number Methods and Interesting Things


● toString(); //Returns a number as a string
● x.toFixed(2); // Returns a string, with the number written with a specified number of decimals
● toPrecision(); //Returns a string, with a number written with a specified length

● Number() // Returns a number, converted from its argument.


● parseFloat() // Parses its argument and returns a floating point number
● parseInt(“10.33”) → 10 // Parses its argument and returns an integer

Dates
The ISO 8601 syntax (YYYY-MM-DD)
var d = new Date("Jan 5, 2022 15:37:25")

Get Methods
● getFullYear() //Get the year as a four digit number (yyyy)
● getMonth() //Get the month as a number (0-11)
● getDate() //Get the day as a number (1-31)
● getHours() //Get the hour (0-23)
● getMinutes() //Get the minute (0-59)
● getSeconds() //Get the second (0-59)
● getMilliseconds() //Get the millisecond (0-999)
● getTime(); //Get the time (milliseconds since January 1, 1970)
● getDay() //Get the weekday as a number (0-6)
● Date.now() //Get the time. ECMAScript 5.

Set Methods
● setDate() //Set the day as a number (1-31)
● setFullYear() //Set the year (optionally month and day)
● setHours() //Set the hour (0-23)
● setMilliseconds() //Set the milliseconds (0-999)
● setMinutes() //Set the minutes (0-59)
● setMonth() //Set the month (0-11)
● setSeconds() //Set the seconds (0-59)
● setTime() //Set the time (milliseconds since January 1, 1970)

Math Methods
abs(x) //Returns the absolute value of x
acos(x) //Returns the arccosine of x, in radians
acosh(x) //Returns the hyperbolic arccosine of x
asin(x) //Returns the arcsine of x, in radians
asinh(x) //Returns the hyperbolic arcsine of x
atan(x) //Returns the arctangent of x as a numeric value between -PI/2 and PI/2 radians
atan2(y, x) //Returns the arctangent of the quotient of its arguments
atanh(x) //Returns the hyperbolic arctangent of x
cbrt(x) //Returns the cubic root of x
ceil(x) //Returns x, rounded upwards to the nearest integer
clz32(x) //Returns the number of leading zeros in a 32-bit binary representation of x
cos(x) //Returns the cosine of x (x is in radians)
cosh(x) //Returns the cosine of x (x is in radians)
exp(x) //Returns the value of Ex
expm1(x) //Returns the value of Ex minus 1
floor(x) //Returns x, rounded downwards to the nearest integer
fround(x) //Returns the nearest (32-bit single precision) float representation of a number
log(x) //Returns the natural logarithm of x
log10(x) //Returns the base-10 logarithm of x
log1p(x) //Returns the natural logarithm of 1 + x
log2(x) //Returns the base-2 logarithm of x
max(x, y, z, ..., n) //Returns the number with the highest value
min(x, y, z, ..., n) //Returns the number with the lowest value
pow(x, y) //Returns the value of x to the power of y
random() //Returns a random number between 0 and 1
round(x) //Rounds x to the nearest integer
sign(x) //Returns the sign of a number (checks whether it is positive, negative or zero)
sin(x) //Returns the sine of x (x is in radians)
sinh(x) //Returns the hyperbolic sine of x
sqrt(x) //Returns the square root of x
tan(x) //Returns the tangent of an angle
tanh(x) //Returns the hyperbolic tangent of a number
trunc(x) //Returns the integer part of a number (x)
Regular Expression (Regex)

General
/e/g → Matches globally e separately
/e+/g → Matches singles e and consecutives e (bee)
/e+a?/g → Matches e´s with a consecutive a. But continue matching e´s obligatorily
/ea*/g → Matches ea together, but consecutive e´s separately. (Beaan is selected together)
.
/ea /g → Matches the next letter of this combination. (Beat)

Slash and Parentheses (w/s/d)


. . .
/\ / → Cancel the special signifier of “ ” (My heart )

/\w/ → Matches all the words separately


/\s/ → Matches any form of whitespace

/\W/ → Matches any form of whitespace


/\S/ → Matches all the words separately

/\w{4}/ → Matches a minimum and maximum value (Heart → Hear → was)


/\w{4-5}/ → Matches words between 4 (minim) to 5 (maxim) (Created, Text, are)

/\d{2,5}/g → Matches digits. First minimum, next maximum

Brackets (Match more than one letter)


/[fc]at/g → Words who begin in f or c and finish in at (Cat, Fat, At, Forecat)

/[a-z]at/g → Words who finish in at and begin with whatever abc word (Zat, Create, Matched)
/[A-Z]at/g → First letter in uppercase (Pattern)

/[0-9]at/g → First letter a number between 0-9 (9at, 11at)

Braces
/(t|T)/g → Matches t or T
/(t|B)he/g → Matches the and Bhe

/(t|e|r){2,3}/g →. If there are words with a combination of three and next another in question
letter, they are separated by a space. In other words, at least must have a combination
between 2 of the letters, and the maximum of letters combinated is 3. (Expression, Reg,
See) (Stre et → Seeet) This last is taken like two separate words

(t|e|r){1,4}/g → (stree ts, bat)


(re){1,3}/g → This is for a group of words with re. (rerere rerere rereer, re)
(re){2,4}/g → This is for a group of words with re. (rererere rererere rerereer, rere, re)

^ Symbol
/^T/g → Select the first letter of the first line (The white…..)
/^T/gm → Select the first letter of each new line (The white…. The butterfly … My … The ill)

. .
/\ $/g → Select last “ ” in the last line unless you active “m” = multiline

Look Behind
/(?<=[Tt]he)./g → All the spaces followed by T/t he
/(?<![tT]he)./g → The unique space is that who is next to T/t he

Look Ahead
/.(?=at)/g → Any character before at
/.(?!at)/g → Before at isn´t selected. Everything is followed by at

Practice
/\d{3}[ -]?\d{3}[ -]?\d{4}/g → With (?) we say (-) is optional. (123456780, 123-456-7890, 123
456 7890)

/([:;])([-~])?([D)])/g

JSON (Javascript Object Notation)


Example of an Array
// This array was called “x” for later
{
"employees":[
{"firstName":"John", "lastName":"Doe"},
{"firstName":"Anna", "lastName":"Smith"},
{"firstName":"Peter", "lastName":"Jones"}
]
}

Convert JSON to Javascript


var text = later;
var obj = JSON.parse(text);
The JSON format is syntactically identical to the code for creating JavaScript objects, for that
you can convert JSON data into native javascript objects.

Debugging
Works to find problems before you can´t see. You should look for more of this.

DOM (Document Object Model)

Change Styles, Content and Attribute


● element.innerHTML = new html content
● element.style.property = new style
● element.setAttribute(attribute, value) //For src in a image like element.src=x-x

Adding and Deleting Elements


● document.createElement(tagName)
● target.removeChild(element)
● target.appendChild(element) // Add a HTML element
● target.replaceChild(new, old)
● document.write(text)
● target.createTextNode("Hello!");

Example
// Adding a new element before the elements who has been created at that moment
paragraph1 = parentDiv.firstChild;
parentDiv.insertBefore(newParagraph, paragraph1);

Inner HTML & Node Value


<h2>Do <em>not</em> hit!</h2> // innerHTML
<h2>Do <em>not</em> hit!</h2> // nodeValue

Note: You can use innerHTML to add new HTML elements to a single element.

e.g., demo.innerHTML = "<li>Marcus</li><li>Elizabeth</li>"

Nodes & Properties


// Access to the demo node value
var myTitle = document.getElementById("demo").firstChild.nodeValue;
var myTitle = document.getElementById("demo").childNodes[0].nodeValue;
var myText = document.getElementById("demo").childNodes;

var myFinalTitle = document.getElementById("demo").lastChild.nodeValue;


var myFather = document.getElementById("demo").parentNode.nodeValue;
var mySiblingP = document.getElementById("demo").previousSibling.nodeValue;
var mySiblingN = document.getElementById(“demo”).nextSibling.nodeValue;

var nameTarget = document.getElementById(“demo”).nodeName;

// Getting node type. Gives a number. 1 for div´s, p´s; 3 for text nodes
var nType = targetNode.nodeType;

Useful Examples
// This is a collection because is used a tagname
<script>
document.getElementsByTagName("p")[0].innerHTML = "Hello";
</script>

Events
onchange An HTML element has been changed
onclick The user clicks an HTML element
onmouseover The user moves the mouse over an HTML element
onmouseout The user moves the mouse away from an HTML element
onkeydown The user pushes a keyboard key
onload The browser has finished loading the page

onload // When the user enter to the page


onunload // When the user leaves the page
onchange // When the value in an input changes for example
onmouseover // Same than hover
onmouseout // When you ward off the cursor
onmousedown
onmouseup
onclick
onblur // When the user leaves to focus an input

document.getElementById(id).onclick = function(){code}
element.addEventListener(event, function, useCapture);

Note: The argument passed by the anonym function in an event listener is the event itself.
form.addEventListener("submit", (e) => {
e.preventDefault(); // This works to avoid the default action of a submit events that is refresh the page
const todo = document.getElementById("todo");
const todoval = todo.value;
console.log(todoval);
todo.value = ""; // This is for empty the input value after this is put in it
})

Focus and Blur Events


Email:<br>
<input type="text" size="30" onFocus="this.style.backgroundColor='yellow';"
onBlur="this.style.backgroundColor='white';">

Focus is when the input field is selected, and blur is when the input field is unselected.

Submit Event
<form onSubmit="checkAddress('email');">
Email:
<input type="text" id="email">
<input type="submit" value="Submit">
</form>

function checkAddress(fieldId) {
if (document.getElementById(fieldId).value === "") {
alert("Email address required.");
}
}

Storage
localStorage.setItem(key, element) // Which password I will use, and which element I want to save
localStorage.getItem(key) // Call my element again even after refresh

Short Circuit
localStorage.getItem() || []; // First value is null, for that I will use an empty array instead

Note: This code isn't Javascript at all. For that reason we must use JSON.parse()

const todos = JSON.parse(localStorage.getItem(‘todos’)) || [];

Now, you must stringify the values you put inside of the local storage

todos.push(todoVal);
todos todostrings = JSON.stringify(todos);
localStorage.setItem(‘todos’, todostrings);
Relevant Keywords

This Keyword
In a function definition, this refers to the "owner" of the function

var plan1 = {
name: "Basic",
price: 3.99,
space: 100,
transfer: 1000,
pages: 10,
discountMonths: [6, 7],
calcAnnual: function(percentIfDisc) {
var bestPrice = this.price;
var currDate = new Date();
var thisMo = currDate.getMonth();
for (var i = 0; i < this.discountMonths.length; i++) {
if (this.discountMonths[i] === thisMo) {
bestPrice = this.price * percentIfDisc;
break;
}
}
return bestPrice * 12;
}
};

Length Keyword
Take the length of an element. Works for Strings, Arrays.
var txt = "Hello World!";
var x = txt.length;

var myArray = [“Fruits”, “Vegetables”, “Carbohydrates”];


var arrayLength = myArray.length;

New Keyword
Become a string or a number in an object.
var x = "John";
var y = new String("John");
x==y (true)

var x = 123;
var y = new Number(123);
Interesting Things

Decimals Control
Use the method .toFixed(2). As an example you have 10.654498, but you can only have 2
decimals rounded, use your variable and with this method specify how many decimals you
want.

var priceShirt = 9.95;


var taxes = 6.5%;
var total = priceShirt + (priceShirt * taxes); // 10.59675

var prettyTotal = total.toFixed(2); // 10.60

Note: To round a number to no decimals leave empty the method value.

Countdown Explained in Book


Smarter Way Js (106)

Avoid link tag redirect to same page


<a href="JavaScript:void(0)" onClick="alert('Hi');">Click</a>

Template Literal
`Juice with ${apples} apples and ${oranges} oranges.`
Note: To do the symbols use (ctrl + alt + } btn) * 2 // It´s a shortcut

It's useful to use the parameters as strings.

Form Validation - Text Fields


<form action="" onsubmit="return checkForLastName()">
<label for="lastName">Enter your lastName</label>
</br>
<input type="text" id="lastName">
</br>
<input type="submit" value="Submit">
</form>

<p id="test"></p>

function checkForLastName() {
// let lastName = document.getElementById("lastName");
let test = document.getElementById("test");
if (lastName.value.length === 0) {
test.innerHTML = "Enter your last name"; // To do this you need to return the function in the event
lastName.focus();
lastName.style.background = "blue";
// alert("something");
return false; // This is for no share the data
}
lastName.style.background = "white";
}

Form Validation - Dropdowns


<form onSubmit="return checkForSelect('states');">
<select id="states">
<option value="" selected="selected">SELECT A STATE</option>
<option value="AL">Alabama</option>
<option value="AK">Alaska</option>
<option value="AZ">Arizona</option>
<option value="AR">Arkansas</option>
</select>&nbsp;&nbsp;
<input type="submit" value="Submit">
</form>

function checkForSelect(selecID) {
let target = document.getElementById(selecID);
if (target.selectedIndex === 0) {
alert("Select a State bro");
return false;
}
}

Form Validation - Radio Buttons


<form onSubmit="return validateRadios('distintc')">
<input type="radio" name="distintc" value="Male">Male <br>
<input type="radio" name="distintc" value="Woman"> Woman <br>
<input type="radio" name="distintc" value="Nothing"> Nothing <br>
<input type="submit" value="Submit">
</form>

function validateRadios(eName) {
let radios = document.getElementsByName(eName);
for (let i = 0; i < radios.length; i++) {
if (radios[i].checked) {
return true;
}
}
alert("Please check one");
return false;
}

Exceptions Try and Catch


function greetWorld() {
try {
var greeting = "Hello world!";
aler(greeting);
}
catch(err) {
alert(err);
}
}

greetWorld();

Practices / Projects

To Do List
<form id="todo-form">
<input type="text" id="todo">
<input type="submit" value="Send">
</form>

<ul id="todo-list"></ul>

const todos = JSON.parse(localStorage.getItem('todos')) || [];

const render = () => {


todo.value = "";
const todoList = document.getElementById("todo-list");

const todosTemplate = todos.map(t => "<li>" + t + "</li>"); // t in this case is the same as say todos[i]. And if you use {} you must use return

todoList.innerHTML = todosTemplate.join(""); // You must use join because you can´t call an array in HTML. With join you specify the separation between elements

const elements = document.querySelectorAll("#todo-list li");

/* First argument is the element we are iterating. Second argument we have the index of that element. The
different with map is which this can't be assigned to a constant*/
elements.forEach((element, i) => {
element.addEventListener("click", () => {
element.parentNode.removeChild(element);
todos.splice(i, 1);
actualizeTodos(todos);
render(); // This actualizes the index because the function is recharged. It's A callback too
})
})
}

const actualizeTodos = (todos) => {


const todoStrings = JSON.stringify(todos);
localStorage.setItem('todos', todoStrings);
}

window.onload = () => {
render(); // This is for charge all our <li> once the page is recharged again
const form = document.getElementById("todo-form");
form.addEventListener("submit", (e) => {
e.preventDefault();
const todo = document.getElementById("todo");
const todoVal = todo.value;
todos.push(todoVal);
actualizeTodos(todos);
render();
})

Notes
1. Don´t name your variables only “name”. Name them “namePerson” or something like
that. This is because the named declaration can cause issues.
2. Expressions are those lines of code that produce a value (Num, Booleans, Str).
Statements are big pieces of code that don't execute a value (Conditionals).
3. A simple function is a function declaration. An anonymous function is a function
expression (This includes an arrow type too).
4. Algorithms are made through while loops, regex, forin, forof

List of Items to practice

Switch Conditional

Return Keyword

You might also like