Jump to reference ... All General Declaration HTML DOM Loops

Laurainda's Javascript Reference

General
Comments
// Single line comments
/* Multi line comments */
For text that acts as comments
Console log
console.log("Some text");
Display message to console, which is usually used during develpment or for debugging.
Alert
alert("Some text");
Pop up an alert box in browser.
Prompt
myAns = prompt("Question","Initial answer");
Pop up an input box in browser with initial answer (optional). Return with user input.
Declarations
Variables
var myVal;
var arr = ["arr1","arr2", "arr3"];
let myVal2 = "some value";
const PI = 3.1415;
Declare a variable. Keyword "const" has to be initialized with value, which cannot be re-assigned.
Objects
let myStruc = {
	value1=1,
	value2="two",
};
myStruc.value1 = 2;
myStruc["value2"] = "one";
Declare an object with "let". Access object properties with the bottom two lines.
Functions
function myFunction(myParam) {
	//some code...
	return "Some value";
}
myFunction("Some Parameters");
Declare and use a function. Parameters and returns are optional.
HTML DOM (Document Object Model)
Finding HTML element
myVar1 = document.getElementById(id);
myVar2 = document.getElementsByTagName(name);
myVar3 = document.getElementsByClassName(name);
Identifying HTML element by ID, name, class name
Changing HTML elements
element.attribute = new value;
element.setAttribute(attribute, value);
Changing the attribute value of an HTML element.
Create HTML element
myVar = document.createElement(element);
Create an HTML element. Need to attach it to some other element.
Add an HTML element
myElement.appendChild(newElement);
Add newElement as a child of myElement.
Delete an HTML element
myElement.removeChild(oldElement);
Remove oldElement from myElement.
Replace an HTML element
myElement.replaceChild(newElement, oldElement);
Replace oldElement with newElement.
Loops
For loop
for (var i=0; i< myMax; i++){
  // do something
}
Loop with iterations from i=0 to myMax-1.
While loop
While (i < myMax) {
  // do something
}
Evaluate i < myMax, and then do action in loop until condition becomes false.
Do While loop
do {
  // do something
} while (i < myMax)
Do actions in the loop, then evaluate whether i < myMax.
Break
while (myVar) {
  // actions 1
  break;
  //actions 2
}
Preform action 1, skip action 2, and exit loop.
Continue
while (myVar) {
  // some actions 1
  continue;
  //some actions 2
}
Preform action1, skip action 2, then go back to the top of the loop for evaluation of condition.