Learning Javascript Cheat Sheet

A Programming › JavaScript cheat sheet in English by kelt
19,261 views 5,322 downloads 5 May 2016 History
4.5 avg · 6 ratings

Comments

// single line comment
//  great place to store your thoughts

/*
    this is a multi-line comment
    everything in here is ignored
*/

Conditions

if (person.favoriteColor === 'red') {
    // give person a rose
}
else if (person.favoriteColor === 'blue') {
    // give person a violet
}
else {
    // tell person a poem
}

Loops

var year = 2016;

while (year < 2020)
{
   console.log("Party like it's ", year);

   // shorthand for: year = year + 1;
   year++;
}


for (var year = 2016; year < 2020; year++)
{
   // no need to increment year in here
   // because it is done in the for loop

   console.log('...', year);
}

Scope

// Scopes are controlled by brackets { }
// an **outer** scope cannot use variables
// declared inside **inner** scopes
// but an **inner** scope can use variables
// declared in the **outer** scope

// outside scope
var x = 1;
var y = 2;
var z = 3;
var result;

function testingScope ( z )
{
   // new variable inside function scope
   var w = 4;

   // y is scoped to this function
   // doesn't affect outer y
   var y = x;  
   
   // z is a function parameter
   // so it's scope is local to function
   z = z + w;  

   // updating x in **outer** scope
   x = 2;       

  return z;   // returns 8
}

result = testingScope(4);

/*
    w is undefined in outer scope
    x changed to 2
    y is still 2
    z still 3
    result is 8

*/

Variables

var&nbsp;answer&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;42;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;number

var&nbsp;duckSays&nbsp;&nbsp;=&nbsp;'quack';&nbsp;//&nbsp;strings&nbsp;'&nbsp;&&nbsp;"

var&nbsp;isAwesome&nbsp;=&nbsp;true;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;boolean

var&nbsp;emptiness&nbsp;=&nbsp;null;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;null

var&nbsp;catNames&nbsp;&nbsp;=&nbsp;[&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;array&nbsp;of&nbsp;strings
&nbsp;&nbsp;&nbsp;'princess',
&nbsp;&nbsp;&nbsp;'fizzy',
&nbsp;&nbsp;&nbsp;'zoro'
];

var&nbsp;cat&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;=&nbsp;{&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;a&nbsp;single&nbsp;object
&nbsp;&nbsp;&nbsp;name:&nbsp;catName[2],&nbsp;&nbsp;&nbsp;&nbsp;&nbsp;//&nbsp;zoro
&nbsp;&nbsp;&nbsp;age:&nbsp;&nbsp;10
};
answer + 1;
// 43

duckSays + "­qua­ck";
// quack quack

catNam­es[2];
// zoro

cat.age = 11;
// sets cat age to 11

Intervals / Timeouts


function callMeShirley()
{
   console.log('Surely, we can learn Javascript in 20 minutes?!');
}

function dontCallMeShirley()
{
   console.log('Don't call me Shirely');
}

*// runs every 1000 milliseconds (1 second)*
var interval = setInterval(callMeShirley, 1000);

*// runs **once** after 5 seconds*
var timeout = setTimeout(dontCallMeShirley, 5000);

DOM / Document Object Model

The power to find, remove, replace, clone and create new html inside your web page

Nodes are different little bits and pieces of html

All nodes have a type (we can find it using, node.n­ode­Type)

ATTRIB­UTE­_NODE
CDATA_­SEC­TIO­N_NODE
COMMEN­T_NODE
DOCUME­NT_NODE
DOCUME­NT_­FRA­GME­NT_NODE
ELEMEN­T_NODE
TEXT_NODE
... and a dozen others omitted ...


Elements are nodes that have a nodeType of ELEMEN­T_NODE such as

<di­v>
<p>
<a>

button element node
var button = docume­nt.g­et­Ele­men­tBy­Id(­'­spe­cia­lBu­tto­n');

array of element nodes
var buttons = docume­nt.g­et­Ele­men­tsB­yCl­ass­Nam­e('b­utt­on');

new element node
var node = docume­nt.c­re­ate­Ele­men­t('d­iv');

element node type
node.n­odeType

cloned element node
var clone = node.c­lon­eNo­de(­true);

Functions

function addTogether(x, y)
{
   return x + y;
}

var z = addTogether(1, 2);

Functions (other ways)

var addEm = addTogether;

var add = function(x, y)
{
   return x + y;
}

var myObj = {
   add: function(x, y) {
      return x + y;
   }
}

myObj.addEm = addTogether;
All these functions return 2

addTog­eth­er(1, 1);
addEm(1, 1);
add(1, 1);
myObj.a­dd(1, 1);
myObj.a­dd­Em(1, 1);

Classes / reusable objects

// constructor called for "new Person"
function Person(name)
{
  this.name = name;
}

// all person's that are created will have
// this function available
Person.prototype.changeName = function(newName)
{
  this.name = newName;
}

var person = new Person("Bob");

person.changeName('Sponge');

Events

<button id="clickMe">Surely, You'll Click Me</button>

var button = document.getElementById('clickMe');

button.onclick = callMeShirley;
Often events are a better altern­ative than intervals. Events are fired only when triggered. Intervals happen regard­less. In the above example, callMe­Shirley will only be triggered when the button is clicked.

Here is a list of events

jQuery


**// get mouse position {{link="http://stackoverflow.com/questions/7790725/javascript-track-mouse-position"}}without jQuery{{/link}}**

document.onmousemove = handleMouseMove;

function handleMouseMove(event)
{
  var dot, eventDoc, doc, body, pageX, pageY;

  event = event || window.event;

  if (event.pageX == null && event.clientX != null)
  {
      eventDoc = (event.target && event.target.ownerDocument) || document;
      doc = eventDoc.documentElement;
      body = eventDoc.body;

      event.pageX = event.clientX +
         (doc && doc.scrollLeft || body && body.scrollLeft || 0) -
         (doc && doc.clientLeft || body && body.clientLeft || 0);
      event.pageY = event.clientY +
         (doc && doc.scrollTop  || body && body.scrollTop  || 0) -
         (doc && doc.clientTop  || body && body.clientTop  || 0 );
  }
}


**// get mouse position with jQuery**

$('body').on('mousemove', function(event)
{
   var mousePosition = { x: event.clientX, y: event.clientY };
});

jQuery is a library that can help us when we write javascript for the browser.

As seen in the example above, the jQuery library solves a problem for us. It abstracts away subtle browser incons­ist­encies for us.

Use jQuery whenever you can to make your code easier
to read, understand and maintain. There are also thousands of jQuery plugins too and you are likely to use some to enhance your website.

Badges

Nice Cheat Sheet Good Cheat Sheet Appreciated Cheat Sheet Downloaded from Unusual Locations × 2

Comments

No comments yet.

Cheatography n. The art of mapping complex subjects into clear, instantly navigable reference guides.