JavaScript Basics Cheat Sheet
JavaScript, as it was modelled after other C-like languages, uses two types of comments:
/*
Multi-line comments start with a slash asterisk and
can span
as many lines as desired.
They end with a asterisk slash.
*/
Variables and expressions
Three ways of declaring a variable legitimately (possible to just assign variable a value, but that always becomes global variable and is a bad practice)
- const - Using const technically not a variable as value is a constant and can not change.
- var - was the original way of defining variable but all variables are placed on the function’s scope.
- let - uses the scope of where the variable was defined.
Assignment is with the = symbol. Equality is == and will be discussed in conditionals. When you are assigning a variable, it will be internally represented as one of eight types.
- Number - a number
- String - "text". Use quotes to declare.
- Boolean - can be true or false
- BigInt - an integer with arbitrary magnitude
- Symbol - a guaranteed to be unique object
- Objects - a collection of properties
- Null - used to indicate no variable
- Undefined - used to indicate a variable with no value
Math operations follow normal algebra rules (parentheses, multiplication or division, addition or subtraction). + and - are as you expect. Division is / and multiplication is *. To get the remainder (modulus) use %. As assigning math results using a variable to that variable, such as x = x + 1, is so common, there are shortcuts:
- ++ increment (eg x + 1). ++x increments before applying x, x++ applies value then increments
- -- decrement. same as increment but subtracts 1
- += adds value to variable. x += 3 is same as x = x + 3.
- -= adds value to variable. x -= 3 is same as x = x - 3.
- *= adds value to variable. x *= 3 is same as x = x * 3.
- /= adds value to variable. x /= 3 is same as x = x / 3.
Can also do logical operations. & is logical and, | is logical or ^ is xor >> is shift right, << is shift left. >>= and <<= are shortcuts.
Strings
Strings are immutable. Can use " or ' for strings, can have opposite symbol. For templates, ´ is used. ´used to easily show ${variable}´ length property gives number of characters in string. Common Methods:
- charAt() returns character at index (nrgative counts back from end)
- charCodeAt() same as charAt but returns UTF-16 code
- concat() same as adding strings
- endsWith() checks if last characters match string
- includes() checks if provided string contained within string
- indexOf() finds first index of provided string with optional start index, -1 if not in string
- lastIndexOf() same as index of but from end
- replace() replaces occurrences of first string with second string
- slice() returns substring between start and ending indexes (not including ending index character)
- split() breaks string into array based on split string. will cover arrays later.
- substring() same as slice but will order indexes
- toLowerCase() converts string to lower case
- toUpperCase() converts string to UPPER CASE
- trim() removes whitespace from beginning and ending of string
- trimEnd() removes whitespace from ending of string
- trimStart() removes whitespace from beginning of string
Math functions
A holdover from Java. Math function not built in but part of library. Common variables:
- Math.E is the base of natural logarithms aka Euler's number
- Math.PI is the ratio of a circle's circumference to its diameter
methods are static so you must specify Math. Common methods:
- Math.abs() the absolute value
- Math.acos() the arccosine
- Math.acosh() the hyperbolic arccosine
- Math.asin() the arcsine
- Math.asinh() the hyperbolic arcsine
- Math.atan() the arctangent
- Math.atan2() the arctangent of the quotient of the arguments
- Math.atanh() the hyperbolic arctangent
- Math.cbrt() the cube root
- Math.ceil() the smallest integer greater than or equal to provided value
- Math.cos() the cosine
- Math.cosh() the hyperbolic cosine
- Math.floor() the largest integer less than or equal to provided value
- Math.hypot() the square root of the sum of squares of the arguments
- Math.log() the natural logarithm
- Math.log10() the base-10 logarithm
- Math.log2() the base-2 logarithm
- Math.max() the largest of the provided numbers
- Math.min() the smallest of the provided numbers
- Math.pow(x, y) x to the power of y
- Math.random() Generates a pseudo-random number between 0 and 1
- Math.round() rounds number to nearest integer
- Math.sign() -1 if negative, 0 if 0, 1 if positive
- Math.sin() the sine
- Math.sinh() the hyperbolic sine
- Math.sqrt() the positive square root
- Math.tan() the tangent
- Math.tanh() the hyperbolic tangent
- Math.trunc() the integer portion of the provided value
Conditional Statements
if (condition)
statement_to_perform_if_condition_is_true
else
statement_to_perform_if_condition_is_false
Condition operators:
- == equals
- === strictly equals (same type)
- != not equals
- !== strictly not equals (same type)
- < less than
- <= less than or equals
- > greater than
- >= greater than or equals
- ! not (flips true/false)
- && and
- || or
Switch Statements
Switch statements are a condensed way of having several if statements. One advantage they have over if statements is that condition code can flow through multiple cases. This is also the biggest disadvantage as it is easy to forget a break statement. The following if statement:
console.log("The number is one");
} else if (number == 2) {
console.log("The number is two");
} else if (number == 3) {
console.log("The number is three");
} else {
console.log("The number is not one, two or three");
}
is equivalent to the following switch statement:
case 1:
console.log("The number is one");
break;
case 2:
console.log("The number is two");
break;
case 3:
console.log("The number is three");
break;
default:
console.log("The number is not one, two or three");
}
Functions
Functions can be defined using the function statement and return a value with return. Calling a function is done by using the name of the function
return x * x;
}
console.log(`square of 8 is ${squared(8)}`);
They can also be assigned to a variable.
console.log("square of 7 is " + square(7));
There is a shortcut (used for lambdas which will be in a future cheat-sheet)
console.log("square of 6 is " + sqr(6))
Loops
Doing things multiple times, we have the for loop:
console.log(`i is ${i}.`);
}
While loops loop until a condition is met. The above for loop is essentially a macro for a while statement. here is the for loop written as a while:
while (i < 10) {
console.log(`i is ${i}.`);
++i;
}
Do..while loops are while loops but will always run at least one time:
do {
console.log(`i is ${i}.`);
++i;
} while (i < 10);
Accessing Elements
We will assign elements we wish to access a unique id using the id tag as follows:
Then within a script section you can access the element using something like:
It lets us put something between the <p> and </p> (or whatever tag you are using). Example:
Notice that the string you are using can have other tags inside of it!
Borders, and other tags that have - in them are not proper JavaScript variables so use camelCase instead
myText.style.backgroundColor = "#CAF";
myText.style.borderBottom = "5px solid red";
We will continue our coverage of JavaScript in the JavaScript Classes cheat sheet.