Cheat Sheet: Javascript

style guide for coding

datatype: number, string, boolean

typeof(): return data type

prompt(): pop up window with user text input area

var: define a variable, only needed when you create it


String

“a” + “b” // string concatenation

myVar.length; // get the length of the string

myVar.slice(0, 4); /// myVar= “abcdef”,  startPosition=0, endPosition but not include 4, return “abcd”

myVar.toUpperCase(); /// myVar= “abcdef”,  return “ABCDEF”, similar .toLowerCase()

Arithmetic

10 % 4 // modulo operator, return the reminder 2

x++ // equal to x=x+1, similar x--

x+=2 // equals to x=x+2, similar x-=2, x*=2, x/=2

math.floor(4/1.5) // rounddown, return 2

var n = A+math.floor(math.random()*B) // return random number between A and B


Function

function functionName() { … } // basic format, no ; at the end

function functionName(input1, input2, ...) { … } // allow to get the inputs such as variables

function functionName(input1, input2, ...) {

return result;  // define what is the output

}

Conditionals & Logic

if(conditions) {  // basic format of if-else control

code;       // for conditions, === equal both in value and data type <-> !==

} else if (conitions) {       // for conditions, == equal in value regardless of data type <-> !=

code;

} else (conitions) {      

code;

}

 

if ( conditionA && conditionB) {…} // and

if ( conditionA || conditionB) {…} // or

if ( !conditionA) {…} // not

Array

var myArray = [“a”, “b”, “c” ] // create an Array

myArray.length // counts the number of elements in the array

myArray.includes(“a”)   // check if an array contains a certain string, return True or False

myArray.push(“d”) // add an element to the end of the array

myArray.pop() // return the last element and remove the last element of the array

 

Loops

while (conditionA) {…} // run the code repeatedly when conditionA is met, aka stop when conditionA is not met

for (startPoint; endpoint; change) {…} // run the code repeatedly from “startPoint” to “endpoint” condition, each time make changes according to “change”

switch (myVariable) {

case expression1: // if myVariable = expression1, do code 1;

  code 1;

break;

case expression2: // if myVariable = expression2, do code 2;

  code 2;

break;

 

default: // if myVariable <> any expression above, do code 3;

 code 3;


Add Javascript to Website

<body onload= “alert(‘hello’) ” // inline javascript

<body> …

<script type= “text/javascript”> … </script>

</body> // internal javascript

<body> …

<script src= “index.js” charset=”utf-8”></script>

</body> // connect to external javascript


Manipulatie with DOM

<h1><a href=“/home.com”>title</a><h1>

document.getElementsByTagName(“h1”).classList.add(“newClass”) // add a new class to h1 tag, <h1 class=“newClass”> similar classList.remove, classList.toggle

document.getElementsByTagName(“h1”).textContent// return “title”, v.s. .innerHTML return <span>title</span>

document.querySelector(“a”).attributes// return the attributes of element with tag a

document.querySelector(“a”).getAttribute(“href”)// return “/home.html”

document.querySelector(“a”).setAttribute(“href”, “/contact.com”)// change the href webpage to “/contact.com”

document.querySelector(“a”).addEventListner(“click”, myFunction); // when a is clicked, call  “myFunction”, do not add () after myFunction

document.addEventListner(“keydown”, function(event){

  myFunction(event.key)

}

); // trigger myFunction with the input of the key that is pressed

Constructor Function

Function MyConstructor (name, age, hasWorkPermit, yearsOfExperience){ // function name Capitalize

this.name = name;

this.age = age;

this.hasWorkPermit = hasWorkPermit;

this.yearsOfExperience = yearsOfExperience; 

this.buildHouse = function (){…};  // define a function, no need to include as input

}

var constructor1 = new MyConstructor(“Tom”, 30, “Yes”, 10) // initialize object, need to add new in front

constructor1.buildHouse()// call the function buildHouse, need to add ()

constructor1.name // return the property name of constructor1, no need to add ()

 

JQuery

<body>

<script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script>

<script scr= “index.js” charset=”utf-8”></script>

</body> // in html, add JQuery link right above the javascript file link

$(“h1”).css(“color”); // return the color property of h1

$(“h1”).css(“color”, “red”); // change the color of h1 to red

$(“h1”).addClass(“myCSS”); // add a class to h1, similar .removeClass

$(“h1”).hasClass(“myCSS”); // check if h1 has class “myCSS”, return True or False

$(“h1”).text(“new title”); // change the text of h1 to  new title

$(“h1”).html(“<strong>new title</strong>”); // change the element under h1

$(“a”).attr(“href”); // get the attribute “href” of a

$(“a”).attr(“href”, “www.google.com”); // change the attribute “href” of a to www.google.com

$(“img”).on(“click”,function(){…}); // add event listeners “click” to img

$(“h1”).before(“<button>button</button>”); // add a button before h1, similar after, prepend, append

$(“img”).remove(); // remove img, similar .hide .toggle .fadeout .fadein .toggleout .slideup etc.

$(“h1”).animate({opacity: 0.5}); // change the opacity of h1 to 0.5, animate only works with numeric ones, need {} inside ()

$(“img”).slideup().slidedown().animate({opacity: 0.5});  // you can put a chain of actions to one element