Show Menu
Cheatography

JavaScript Cheat Sheet (DRAFT) by

This is a draft cheat sheet. It is a work in progress and is not finished yet.

Data types

strings
"some text"
numbers
5 | 12
booleans
true | false | 5 > 3 (true)
arrays
[data, data, data];

Comparison operators

>
Greater than
<
Less than
<=
Less or equal
>=
Greater or equal
===
Equal to
!==
Not equal to

Operators

a = a + 1
a++
a = a - 1
a--
a = a + b
a += b
a = a - b
a -= b
a = a * b
a *= b
a = a / b
a /= b
a = a % b
a %= b

isNaN

isNaN(­'smth')
true
isNaN(NaN)
true
isNaN(­und­efined)
true
isNaN(15)
false

Logical operators

&&
and
||
or
!
not
 

String Properties and Methods

.length
Return the number of characters in a string
.subst­ring()
Extract characters from a string,
var str = "­Hello world!­"; 
var res = str.su­bst­ring(1, 4);
-> ell

If else

if (condition1) {
    // code
} else if (condition2) {
    // code
} else {
    // code
}

Functions

var doStuff = function (par1, par2) {
   value = par1 + par2;
   print value;
}

countSomeStuff(par1,par2);

FOR loop

for (var i = 1; i < 11; i = i + 1) {
    // code
}

While

var x = true;
while ( x === true) {
 // code
 x = false // to stop loop
}

Case Switch

switch ( x ) {
    case 'option1':
        // code
        break;
    case 'option2':
        // code
        break;
    case 'option3':
        // code
        break;
    default:
       // code
}

Objects

var myObject = {
    key: value,
};

var emptyObj = {};

var myObj = new Object();

myObj.name = "Tom";

loop over the keys of an object:
for (var x in object) {
  // code
}

Create class for ogject:

function Cat(name, breed) {
    this.name = name;
    this.breed = breed;
}
var cheshire = new Cat("Cheshire Cat", "British Shorthair");

if you want to add a method to a class such that all members of the class can use it, we use the following syntax to extend the prototype:

className.prototype.newMethod =
function() {
 // code
};