Having an adequate environment to write code is essential for checking spelling and color-code the lines in order to visually highlight code steps. Consider using Visual Studio Code [Link] or Sublime Text [Link].

sudo apt install code -y
sudo apt install sublime-text -y

There are many web applications that allow you to write and execute javascript that deserves to be listed and used for tests and study purposes: Scrimba [Link] and Codepen [Link].


COMMENTS

// this is a comment, ignore this line

/*
this is a comment, ignore all the the lines between this tags
*/

DATA TYPES

  • Undefined
    • variable created and not defined yet.
  • Null
    • has no value applied, means nothing.
  • Boolean
    • true/false or 1/0.
  • String
    • can be a text, a sequence of characters, etc.
  • Symbol
    • an immutable primitive value that is a unique value.
  • Numbers
    • numeric values.
  • Object
    •  can store many different key values.

DECLARING VARIABLES AND CONSTANTS

var globalVariable;

let scopedVariable = "content";

const CONSTANTNAME = "content";

PRINT TO CONSOLE

console.log(varNameB);
console.dir(document)

MATH OPERATORS

var numName = 1 + 10;
var numName = 1 - 10;
var numName = 1 / 10;
var numName = 1 * 10;
var numName ++
var numName --
var numName = 1 + 10;
var numName = 11 % 3;
var numName += 10;
var numName -= 10;
var numName *= 10;
var numName /= 10;

ADVANCED MATH

var numName = Math.round(1.75);
var numName = Math.sqrt(9);
var numName = Math.pow(2, 8);
var numName = Math.random();
var numName = Math.floor(5.99);

STRING

var strName = "Hello" + "!";
var strName = "'\"";
var strName = '\'"';
var strName = `'"`;
var strName = '\\\n\t\b\f';
var strName += " concatenate this text to the string.";
var numName = strName.length;
var strFirst = strName[0];
var strLast = strName[strName,length - 1];
var numName = parseInt(strName);
var numName = parseInt("1010100010", 2);
var numName = eval("a * x + b");
var strName = `can have multiple lines
and get variables such as ${numName}`;

SHORTCUTS AND TIPS

string = "this is the \"scape\" character";

string = 'now " doe snot need scape';

string = `now " and ' can be used freely`;

concatenate = "string1" + "string2";

append += "appends this string at the end";

string = "\'\"\\\n\r\t\b\f";

length = string.length;

secondCharacter = string[1];

lastCharacter = string[string.length - 1];

convertObjectsToString = JSON.stringify(object);

randNumber = Math.random();

convertToInteger = parseInt("100");
convertToDecimal = parseInt("100101100", 2);

variable = a > b ? true : false;

variable = a > 0 ? "positive" : num < 0 ? "negative" : "zero";

"use strict";

Object.freeze(objectName);
var magic = () => new Date();

const {attrib1 : a , attrib2 : b} = { attrib1: "A", attrib2: "B" };

const [z , , , , , y] = [1, 2, 3, 4, 5, 6];

const [a, b] = [b, a];
const [a, b, ...newList] = list;

const [ ,  , ...newList] = list;

const returnObject = (var1, var2) => ({ var1, var2});

const stringName = `text ${variableName}!next line.`;

captalizeFirstCharacterOfString = string.charAt(0).toUpperCase() + string.slice(1);

let x = document.forms["formName"]["elementName"].value;

document.getElementById("inameId").src = "img.jpg";

<form name="formName" action="/page.php" onsubmit="return validateForm()" method="post">

<input type="text" name="elementMame" disabled>

<input type="text" name="elementMame" required>

<button type="button" onclick="document.getElementById('idName').style.color = 'red'">Ack!</button>

<h2>Text</h2><h2 onclick="this.innerHTML='Ooops!'">Click here!</h2>

document.getElementById(id).onclick = functionname(){ // tasks to be executed ; }

EVENT LISTENERS

document.getElementById("buttonName").onclick = funcName; document.getElementById("buttonName").addEventListener("click", funcName);
function funcName(e){
  e.preventDefault();
  console.log(e);
  console.log(e.target.id);
  console.log(e.altKey);
}

var button = document.getElementById('button').addEventListener('click', function(){
  console.log(1);
});

var button = document.getElementById('button');
button.addEventListener('dbclick', funcName);
button.addEventListener('mousedown', funcName);

var table = document.getElementById('table');
table.addEventListener('mouseenter', funcName);
table.addEventListener('mouseover', funcName);
table.addEventListener('mousemove', funcName);

var textBox = document.querySelector('input[type="text']);
textBox.addEventListener('keydown', funcName)
textBox.addEventListener('input', funcName)
textBox.addEventListener('focus', funcName)
function funcName(e){
  console.log(e.target.value);
}

var selec = document.querySelector('select');
select.addEventListener('change', funcName);

var form = document.querySelector('form');
form.addEventListener('submit', funcName);

ARRAYS

var arrayName = ["text", 10];
var arrayName = [["text", 10],[99,True]];
var varName = arrayName[1][0];
arrayName.push("text");
Add the value to the end of the array.
arrayName.unshift("text");
Add the value to the begining of the array.
var varName = arrayName.pop();
Get and remove the last value of the array.
var varName = arrayName.shift();
Get and remove the first value of the array.
arrayOne.concat(arrayTwo);
Concatenate two arrays.
var [ , a, , b] = arrayName;
var [ , , , arr] = arrayName;
var strName = arrayName.toString();
var arrayName.sort();
var arrayName.reverse()

var arrayName2 = arrayName1.map(funcName);
function funcName(value){
return value * 10;
}

var arrayName2 = arrayName1.filter(funcName);
function funcName(value){
return value > 5;
}

var arrayName2 = arrayName1.reduce(funcName);
function funcName(total,value){
return total + value;
}

IMPORT, EXPORT, AND REQUIRE

// in index.js
import { functionName } from "./functions.js";
import PI;

// in functions.js
export const functionName = (var1, var2) => ({ var1, var2});
export const PI = 3.141592653589793238;

// importing everything
import * as objectNameToStoreEveruthing from "functions";

// exporting default
export default function subtract(x,y) {return x-y;};
// importing default
import subtract from "functions";

FUNCTIONS

function functionName(a, b = 2){
console.log(a + b);
declaringGlobalVariable = 10;
var declaringLocalScope = 20;
return (a + b);
};

const functionName = (function() {
return function functionName(...args){
return args.reduce((a,b) => a+b, 0);
};
})();

function* generatorName(){
yield 1;
yield 2;
return 3;
}
let funcName = generatorName();
alert(JSON.stringify(funcName.next()));
alert(JSON.stringify(funcName.next().value));
alert(JSON.stringify(funcName.next().done));

const arrayThree = (arrayOne, arrayTwo) => { return arrayOne.contcat(arrayTwo) };

const arrayThree = (arrayOne, arrayTwo) => arrayOne.contcat(arrayTwo);

function funcName(firstArgument, secondArgument){
return firstArgument + secondArgument;
}

function funcName(...args){
return [...args];
}

var funcExplessionName = function (a, b) { return a + b };

var myFunction = new Function("a" , "b", "return a + b");
var funcName = myFunction(5, 10);

LOGICAL OPERATORS

  • ==
  • !=
  • <
  • >
  • <=
  • >=
  •  ||
    • or
  • &&
    • and
  • ===
    • strict equal (do not try to convert to a common type to compare).
  • !==

CONDITIONS AND LOOPS

if (bolName){
// execute
} elseif (!bolName){
// execute
} else if (numName != 10){
// execute
} else {
// execute
}

while(numName < 10){
numName ++;
// execute
if(numName < 0)
break;
if(numName = 0)
continue;
};

for (let i = 0 ; i < 10 ; i++){
// execute
}

do {
// execute
} while (numName < 10)

switch(numName){
case 1:
strName = "numName is strictly equal to 1";
break;
case "1":
strName = "numName is a string with number 1";
break;
case 100:
case 101:
case 102:
strName = "numName is 100, 101, or 102";
break;
}

OBJECTS

var objName = {
"Name": "John",
"Age": 20,
};
var strName = objName.Name;
var numName = objName["Age"];
delete objName.age;
objName["Family Name"] = "Smith";
var bolName = objName.hasOwnProperty("Name")
var { x : a, y : b, z : c } = objName;

Keywork new to create an Object:

var objName2 = new Object();
objName2.name = "peter";
objName2.age = 30;

CONSTRUCTOR, GETTER, AND SETTER

function objName3(name,age){
this.name = name;
this.age = age
}

class className {
constructor(value){
this._property = value
}
get property(){
return this._property
}
set property(value){
this._property = value
}
}
const objName = new className(100);
var numName = objName.property;
objName.property = 50;
var numName = objName.property;

TERNARY OPERATOR

var strName = a === b ? "equal" : "different";
var strName = numName > 0 ? "positive" : numName < 0 ? "negative" : "zero";

JAVASCRIPT WITH HTML INTERACTION

<html><body>
<script language = "javascript" type = "text/javascript">
document.write("Hello!");
</script></body></html>
<html><body>
<p id="idName"></p>
</body><script>
var arrayName = ["A","B","C"];
document.getElementById("idName").innerHTML = arrayName;

arrayName.forEach((item,index,array) => {console.log(item, index);});
</script></html>
<html><body>
<button id = "idName">Send</button>
</body>
<script>
var
</script>
</html>
<html><body>
<button id="idName">Click</button>
</body>
<script>
document.getElementById("idName").onclick = function(){ alert("Hello!") }
</script>
</html>
<html><body>
<button onclick="funcName()">Click</button>
</body>
<script>
function funcName(){
alert("Hello!")
}
</script>
</html>
<html><body>
<p id = "idName"></p>
</body>
<script>
var objName = {
arrayName: ["A","B","C"],
info(){
this.arrayName.forEach(function(tag){
console.log(tag)
})
}
}
objName.info()
document.getElementById("idName").innerHTML = objName.arrayName;
</script>
</html>
<html><head>
<script type="text/javascript">
function funcName(){
if(document.myForm.email.value == ""){
alert("Insert your e-mail.");
document.myForm.email.focus();
return false
} else {
return true
}
}
</script>
</head><body>
<form name="myForm" onsubmit="return(funcName());" action="/admin">
<input name="email" placeholder="E-Mail" type="text">
<button type="submit">Enter</button>
</form>
</body></html>
<html><head>
<script>
function funcName(){
var email = document.getElementById("email").value;
var regex = /^\[email protected]\S+\.\S+$/;

if (regex.test(email)){
alert("Validated!");
return true
} else {
alert("Not valid!");
document.myForm.email.focus();
return false
}
}
</script>
</head><body>
<form>
<input id="email" placeholder="E-Mail" type="text">
<button onclick="funcName()" type="button">Validate</button>
</form>
</body></html>
<script>
(function(){
alert("Hello!")
})()
</script>

STATES

Promises (multi-threading):

  • Pending
  • Settled
    • Fulfilled
    • Rejected

States:

  • then
    • Callback when resolved/fulfilled.
  • catch
    • Callback when rejected.
<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Title</h1>
<script src="index.pack.js"></script>
</body>
<script>
let actionName = new Promise(function(resolve, reject){
varName = true;
if (varName)
resolve()
else
reject()
});

actionName.then(function(){
document.write("Resolved")
}).catch(function(){
document.write("Rejected")
})
</script>
</html>

PROMISE

<html>
<head>
<link rel="stylesheet" href="index.css">
</head>
<body>
<h1>Title</h1>
<script src="index.pack.js"></script>
</body>
<script>
let actionName = new Promise(function(resolve, reject){
  varName = true;
  if (varName)
    resolve()
  else
    reject()
  }
);

actionName.then(function(){ document.write("Resolved") }).catch(function(){ document.write("Rejected") });
</script>
</html>
<html>
<head>
<title>Items</title>
<script src="https://code.jquery.com/jquery-3.5.0.js"></script>
</head>
<body>
<h1>List of items:</h1>
<form action="" onsubmit="return(sendValidation());" method="post">
<input type="checkbox" id="checked" name="items[]" value="item1" checked>Item 1<br>
<input type="checkbox" id="checked" name="items[]" value="item2">Item 2<br>
<input type="submit" value="Send">
</form>
<script>
function sendValidation(){
  checkBoxCounter = $("input:checked").length;
  if(checkBoxCounter >= 1){
    if (confirm("Do you want to send " + checkBoxCounter + " item(s)?")) {
      return true
    } else {
      return false
    }
  } else {
    alert("You must check at least one item.");
    return false
  }
}
</script>
</body>
</html>
<h1 id="id01">Old Heading</h1>
<script>
const element = document.getElementById("id01");
element.innerHTML = "New Heading";
</script>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = "Hello World!";
</script>

CAPTCHA

<form action="submit.php" method="post" onsubmit="return validateCaptcha();">
<div id="captcha"></div>
<input type="text" placeholder="Type the Captcha here" id="cpatchaTextBox"/>
<input name="submit" type="submit" value="Send" />
</form>
<script>
  var code;

  function createCaptcha() {
    document.getElementById('captcha').innerHTML = "";
    var charsArray = "[email protected]!#$%^&*";
    var lengthOtp = 6;
    var captcha = [];
    for (var i = 0; i < lengthOtp; i++) {
      var index = Math.floor(Math.random() * charsArray.length + 1);
      if (captcha.indexOf(charsArray[index]) == -1)
        captcha.push(charsArray[index]);
      else i--;
    }
    var canv = document.createElement("canvas");
    canv.id = "captcha";
    canv.width = 100;
    canv.height = 50;
    var ctx = canv.getContext("2d");
    ctx.font = "25px Georgia";
    ctx.strokeText(captcha.join(""), 0, 30);
    code = captcha.join("");
    document.getElementById("captcha").appendChild(canv);
  }

  function validateCaptcha() {
    debugger
    if (document.getElementById("cpatchaTextBox").value == code) {
      return true;
    }else{
      event.preventDefault();
      alert("Please type the generated Captcha in the box.");
      createCaptcha();
      return false;
    }
  }

  (function autorun(){ 
    createCaptcha();
  })();
</script>

DOM (Document Object Model)

<div id="div1">
<p id="p1">This is a paragraph.</p>
<p id="p2">This is another paragraph.</p>
</div>
<script>
const paragraph = document.createElement("p");
const node = document.createTextNode("Text or Message");
paragraph.appendChild(node);

const element = document.getElementById("div1");
element.appendChild(paragraph);
</script>

Finding HTML Elements

document.getElementById(idName)
document.getElementsByTagName(tagName)
document.getElementsByClassName(className)

Changing HTML Elements

element.innerHTML = newContent;
element.attribute = newValue;
element.style.property = newStyle;
element.setAttribute(attribute, value);

Adding and Deleting HTML Elements

document.createElement(elementName);
document.removeChild(elementName);
document.appendChild(elementName);
document.replaceChild(new, old);
document.write(text);

Retreving Values from Elements

varName = document.getElementById("example").firstChild.nodeValue;
varName = document.getElementById("example").childNodes[0].nodeValue;
  • parentNode
  • childNodes[nodeNumber]
  • firstChild
  • lastChild
  • nextSibling
  • previousSibling

Finding HTML Objects

document.anchors
document.baseURI
document.body
document.cookie
document.doctype
document.documentElement
document.documentMode
document.documentURI
document.domain
document.embeds
document.forms
document.head
document.images
document.implementation
document.inputEncoding
document.lastModified
document.links
document.readyState
document.referrer
document.scripts
document.strictErrorChecking
document.title
document.URL

Normal Functions vs Arrow Functions

  • Funuction with multiple attributes:
function funcName(a, b){
  return a + b;
}
let funcName = (a, b) => {
  return a + b;
}
let funcName = (a, b) => a + b;
  • Function with a single attribute:
function funcName(a){
  return a;
}
let funcName = a => a;
  • Function with no attribute:
function funcName(){
  return True;
}
let funcName = () => True;

Async and Await with Fetch

async function funcName(){
  const response = await fetch('http://example.com/api');
  const data = await response.json();
  console.log(data);
}
funcName();

Delaying asynchronous function execution:

setTimeout(() => {
  funcName();
}, 1000);

BONUS

Node.js is a backend JavaScript runtime environment that runs code in the server (outside a web browser).

sudo apt install nodejs
node -v
node app.js

Git it a try!


SEE ALSO

CSS Cheat Sheet [Link]

Responsive Design [Link]

HTML Markup Validation Service [Link] – A free web tool that helps with checking markup languages such as HTML for errors on DOM structure.

CSS Markup Validation Service [Link] – Same for CSS.

Link Checker [Link] – Same for broken links.

2 Replies to “Java Script (JS) Cheat Sheet”

Comments are closed.