BRAND: JavaScript Cheat Sheet
JavaScript Cheat Sheet
- Variables:
- Variables are containers for storing data values.
- Arithmetic:
+ - * / %
% is for modulo.
Modulo returns the remainder after integer division.
For example 17 % 7 results in 3 since 17 divided by 7 has a remainder of 3.
- Math Functions:
Math.PI
Math.round()
Math.round( x ) returns the value of x rounded to its nearest integer.
Math.ceil( x ) returns the value of x rounded up to the nearest integer.
Math.floor( x ) returns the value of x rounded down to the nearest integer.
Math.pow()
Math.pow( x, y ) returns the value of x to the power of y.
Math.sqrt()
Math.sqrt( x ) returns the square root of x.
Math.random()
- Returns a random number between
0 (inclusive), and 1 (exclusive).
- Types and Type Casting:
number, string, boolean
typeof( x )
- Returns the type name of
x as a string.
Number( x )
- A function that converts strings to numbers.
Number( "3" ) returns 3
Number( "John" ) returns NaN (Not A Number)
String( x )
- Converts the value of
x into a string.
String( 45 ) converts the number 45 into the string "45"
String( true ) converts the boolean true into the string "true"
- Strings:
+
- Concatenates two strings (puts them together into one string)
- Example:
"Go " + "Navy" evaluates to "Go Navy"
x.length
- Returns the length of string
x.
'Hello'.length returns 5
x.charAt( y )
- Returns the character at position
y in string x.
- Indexing starts at
0.
'Hello'.charAt( 1 ) returns "e"
x.charCodeAt( y )
- Returns the ASCII decimal value of the character at position
y in string x.
"Hello".charCodeAt( 1 ) returns 101
String.fromCharCode( x )
- Returns a string consisting of the ASCII character represented by the decimal value
x.
- Input and Output:
alert( x ) (Output)
- Displays a popup window with the value of
x.
- E.g.
alert("Hello World!");
Produces a popup window that says Hello World!
prompt( x ) (Input)
- Produces a popup window with the value of
x with a text box for the user to enter a value.
- Returns a string of what the user entered into the text box.