Remember: Order of Tag Script: // Always at The Beginning of The Code. No Later of Some Code Because Won T Work This
Remember: Order of Tag Script: // Always at The Beginning of The Code. No Later of Some Code Because Won T Work This
Maybe you could experiment issues when you put the script tag before the HTML element
you want to edit.
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;
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"};
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)
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.
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);
}
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.
Note: You must call the var text if you want to write a text with the elements of array.
Note: Use matchfound to define a code when the loop leaves an undefined value.
Loop for in
Loops through the properties of an Object.
Loop for of
let text = "";
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.
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);
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.";
}
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"
}
}
> 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.
Function parameters are the values received by the function when it is invoked.
Inside the function, the arguments (the parameters) behave as local variables.
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
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.
Callbacks
Use callbacks to actualize a function and take advantage of the scope.
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"}
];
document.body.innerHTML = output;
}
let newVocabulary = (newWord, callback) => {
english.push(newWord);
callback();
}
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.
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.
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.
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;
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))
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;
}
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
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)
/[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)
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
^ 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
Debugging
Works to find problems before you can´t see. You should look for more of this.
Example
// Adding a new element before the elements who has been created at that moment
paragraph1 = parentDiv.firstChild;
parentDiv.insertBefore(newParagraph, paragraph1);
Note: You can use innerHTML to add new HTML elements to a single element.
// 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
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 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()
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;
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.
Template Literal
`Juice with ${apples} apples and ${oranges} oranges.`
Note: To do the symbols use (ctrl + alt + } btn) * 2 // It´s a shortcut
<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";
}
function checkForSelect(selecID) {
let target = document.getElementById(selecID);
if (target.selectedIndex === 0) {
alert("Select a State bro");
return false;
}
}
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;
}
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 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
/* 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
})
})
}
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
Switch Conditional
Return Keyword