This is a draft cheat sheet. It is a work in progress and is not finished yet.
Script tag
In HTML, Javascript must be inserted between the <script> </script> tags. |
window.alert()
window.alert() creates a window alert. For example:
<script>
window.alert(5 + 6);
</script> |
Declaring variables
Muiltiple variables can be declared at once.
var x, y, z
x = 5
y = 1
z = x + y |
Comments
Comments can be used to annotate code, or to prevent execution of code without removing it. It is reccomended to use complete sentences to ensure it is readable. Comments should be updated when code is changed to ensure it remains readable and relevant.
Single line comments start with //
Any code written on this line will be ignored by Javascript.
Multi line comments start with / and end with / |
Function names
Functions should be named like this: functionsNameLikeThis |
Class names
Classes should be named like this: ClassNamedLikeThis |
|
|
Using innerHTML
To access an HTML element, Javascript can use the document.getElementById(id) method.
<h1>My First Web Page</h1>
<p>My First Paragraph</p>
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 5 + 6;
</script>
Javascript has been used above to insert the text into the paragraph. |
Functions
A function is a block of code which performs a task.
A JavaScript function is defined with the function keyword, followed by a name, followed by parentheses (). The code to be executed, by the function, is placed inside curly brackets: {}
function name(parameter1, parameter2, parameter3) {
code to be executed
} |
Variable Names
Variables should be named like this: variablesNamedLikeThis |
Naming Strings
When naming strings it is preferable to use single quotes ' than double quotes "
This is helpful when creating strings which include HTML. |
|
|
Using document.write()
document.write() can also be used
<script>
document.write(5 + 6);
</script>
using console.log()
You can also use console.log() to display data.
<script>
console.log(5+6);
</script> |
Objects
Objects are variables too. But objects can contain many values. This code assigns many values (Fiat, 500, white) to a variable named car:
var car = {type:"Fiat", model:"500", color:"white"}; |
Constants
If a value is constant and immutable it should be named in CONSTANT_VALUE_CASE |
Semi-Colons
Semi-colons should always be used after a statement in JS. Not using semi-colons can lead to problems which are hard to debug. Nethertheless, it is a good habit to get into. |
Naming variables
When naming variables, do not use these reserved words!
abstract else instanceof super
boolean enum int switch
break export interface synchronized
byte extends let this
case false long throw
catch final native throws
char finally new transient
class float null true
const for package try
continue function private typeof
debugger goto protected var
default if public void
delete implements return volatile
do import short while
double in static with |
|