Show Menu
Cheatography

Javascript for Cambridge A Level Cheat Sheet by

Javascript for Cambridge A Level

Script tag

<script type="text/javascript">
  ...
</script>

Basic

// One line comment

/*
Mult-line comment
*/

function addNumbers(a, b){
  return a+b;
}

Button

<button onclick="functionName()">click me</button>

...

<script>
    function functionName(){
        // Write what will happen after button is clicked here
    }
</script>

variables

var a;
create new variable
var a = 10;
create a new variable and assign value
var b = "­som­eth­ing­";
create a new variable and assign string
var c = [1, 12, 31, 45]
create a new array with 4 elements in it
c[0]
access item 0 (first item) in array c

output

consol­e.l­og(a)
Output to browser developer console
docume­nt.w­ri­te(a)
Directly write to end of HTML document
alert(a)
Display popup box with the message
docume­nt.g­et­Ele­men­tBy­Id(­"­xxx­"­).i­nne­rHT­ML=a;
Element ID "­xxx­" content replaced with the message

Input

var a = prompt­("qu­est­ion­", default);
Popup box ask question, assign value to a
var a = docume­nt.g­et­Ele­men­tBy­Id(­"­xxx­"­).value
xxx is a textbox's id, and the value in textbox assigned to a

Loops

// For loop

for(var i=0; i<10; i++){
    document.write(i);
}

// For loop printing everything in array (arr)
// method 1
for (var i=0; i< arr.length; i++){
    document.write(arr[i]);
}
// method 2
for (var i of arr){
    document.write(i);
}

// while loop
// also outputing everything in arr
var i=0;
while (i<arr.length){
    document.write(arr[i]);
    i++;
}

conditions

// If
if (a>b){
  // a > b
}else if (a==b){
  // do when a equals to b
}else{
  // everything else
}

Logical

a==b
equals
a!=b
not equals
a>=b
a larger than or equals b
a <=b
a smaller than or equals b
&&
Logical and, e.g. (3>1) && (3<10), used in if
||
Logical or, e.g. (3>1) || (3<-1), used in if
!
Logical not, e.g. a!=b same as !(a==b)
 

Comments

No comments yet. Add yours below!

Add a Comment

Your Comment

Please enter your name.

    Please enter your email address

      Please enter your Comment.

          Related Cheat Sheets

          Passe Compose Cheat Sheet
          Security+ 601 Exam Cheat Sheet