Correct Coding Style
From Spheriki
This tutorial shall teach you how to code in a style that most are comfortable with due to the ease in reading. Most people who code alone or self teach themselves may start coding in awkward styles. Sometimes more time is put into their awkward styling than there is put into their code. Clean code is neat code, and writing in an orderly fashion helps people understand your code better. Some people may not help those with bad code, simply because it can be a headache to decipher. Therefore following this cheat sheet will make you more susceptible to getting help and attention with your code. It may even be crucial someday if you decide to take programming seriously, since team projects are benefited by clear and clean code.
Contents |
Syntax
A statement is one line, or a group of code:
var my_value = 8;
The identifier is the part that describes what the data is. my_value is an identifier. It describes the integer value of 8.
The keyword describes a unique action that your programming language handles. var is a JavaScript keyword which tells the computer to allocate the space for the integer 8, which was named my_value. Keywords may show up as blue in the editor. You can not use keywords as identifiers. "var var" is illegal.
var my_value = 8+6;
Any math is called arithmetic. Arithmetic can happen within a code statement. "+" is an operation. It adds two operands together. 8 and 6 are operands.
A code block is a statement that has opening and closing brackets: {}.
if (my_value == 14)
{
}
Code blocks can be nested:
if (my_value == 14)
{
if (another_value == 10)
{
}
if (some_value == 5)
{
}
}
In JS, you can nest functions:
function do_something(x)
{
x *= 2;
function inside_function(val) {
return val/2;
}
return inside_function(x);
}
Functions may include multiple code statements. So can loops.
while(my_value == 14)
{
}
Loops can also be nested.
Conventions
When coding conditional statements, and functions you should always keep the brackets level with the identifier. Inner content is tabbed by one tab, which should equal the width of two spaces. There are two methods:
Method 1:
if (my_value == 8)
{
do_something();
}
Method 2:
if (my_value == 8) {
do_something();
}
Also, you can choose to have one-lined conditional statements take no brackets:
if (my_value == 8) do_something();
But be careful with the above practice, it only stops at the first ';' semi-colon. statements after that are not included in the conditional. There is a way of stringing multiple statements together with the ',' comma operator:
if (my_value == 8) do_something, do_another_thing();
But the above syntax is discouraged because this makes the code harder to read. So stick with using single-line conditionals, and use brackets for multi-statement conditionals.
Objects
Objects are weird in JavaScript. JavaScript is not a class-based language. It is a prototype-based language. A prototype-based language builds on objects as a hierarchy rather than treat them as individual classes or entities. Essentially you are always inheriting data. Nevertheless, with closure JS can mimic class-based languages, by making data hiding possible. Closure is when the variables in an object only reside in it. In JavaScript this will represent the private data. Private data and public data are words that dictate the freedom of the data. This is what data hiding is about. Another object can't muck with the private data of a different object. This creates code safety.
First lets write a simple object:
function spaceship()
{
// members:
this.speed = 2;
this.x = 0;
this.y = 0;
// methods:
this.update = function()
{
this.x += this.speed;
this.y += this.speed;
}
}
A member is a value inside an object that represents stored data. It can be public or private. Later you'll see this distinction. Methods are nested functions inside of objects that can perform calculations on the data inside an object. These can also be private and public.
Another way of adding methods to JS objects is by prototyping.
function spaceship()
{
this.speed = 2;
this.x = 0;
this.y = 0;
}
spaceship.prototype.update = function()
{
this.x += this.speed;
this.y += this.speed;
}
But by doing so, you only have access to the public data. Below, you'll see the correct way of handling private data via closure. This is best used when your objects start becoming a bit more advanced.
The correct method of writing a closure-based object in JS:
function spaceship()
{
// private data:
var speed = 2;
var vx = 0;
var vy = 0;
// public data:
this.radians = 0;
this.degrees = 0;
this.x = 0;
this.y = 0;
// public methods: (a is in degrees)
this.setAngle(a) {
if (this.degrees == a) return;
else
{
this.radians = a/180*Math.PI;
this.degrees = a;
vx = Math.cos(this.radians);
vy = Math.sin(this.radians);
}
}
this.update = function() {
this.x += vx * speed;
this.y += vy * speed;
}
}
vx and vy are basic velocity units, they can only modify the content inside the spaceship object. No other object can modify these values. This protects anything malicious from happening. While you might think its weird, well, it is. Data hiding only helps when writing public libraries or if you're working on a team project. If you are working solo and know what your code does, you don't have to worry about data hiding. The above just shows you the proper way of doing it in JS.
Functions
Functions are also weird in JS, because they too are objects. In the above object example, I use the keyword function to denote a JS object. Nesting functions are not a good idea, because they cause less of your code to become reusable. The prime reason as to why you can is so that they are available as a utility rather than a full-blown method. You can not use nested functions outside the function they are nested in! However using the this keyword you can statically bind the function to the object, and it no longer becomes private. Static binding occurs in most programming languages during compile time. In JS, static binding pretty much means its a function you had written in code prior to running the script, JS has no formal static binding so I only talk of it conceptually here, just as I do for data hiding.
function spaceship()
{
// private data:
var speed = 2;
var vx = 0;
var vy = 0;
// public data:
this.radians = 0;
this.degrees = 0;
this.x = 0;
this.y = 0;
// public methods: (a is in degrees)
this.setAngle(a) {
if (this.degrees == a) return;
else
{
this.radians = toRadians(a);
this.degrees = a;
vx = Math.cos(this.radians);
vy = Math.sin(this.radians);
}
}
this.update = function() {
this.x += vx * speed;
this.y += vy * speed;
}
// private methods:
var toRadians = function(v) {
return v/180*Math.PI;
}
}
In the above spaceship example, I created a utility function to calculate the radians from a degree value. Only the spaceship object has access to this private method. Why? This goes back to the idea of keeping your code safe, and in this case your API smaller. An API is a function reference. It describes what the object or group of functions do. By hiding methods such as the toRadians() method, you can exclude this from your API since its something the user will never get to see outside of the object. It's an internal helper.
Object Notation
JS is known for its in-line object creation. These objects are created using a syntax called JSON, or Java Script Object Notation. The code library Json.js can convert your object into a JSON string. But, I'm going to show you how to write one in JS.
var player = {name: "Sam", age: 16};
The above statement creates a JS object and assigns it to values. It is kind-of equivalent to doing this:
function player() {
this.name = "Sam";
this.age = 16;
}
The only problem with a JSON statement is that there is no closure, so private data can't be created. This is treated at JS's equivalent to the struct datatype seen in C-like languages. Let's write the above spaceship model in JSON:
var spaceship = {
speed: 0,
vx: 0,
vy: 0,
radians: 0,
degrees: 0,
x: 0,
y: 0,
setAngle: function(a) {
if (this.degrees == a) return;
else {
this.radians = this.toRadians(a);
this.degrees = a;
vx = Math.cos(this.radians);
vy = Math.sin(this.radians);
}
},
update: function() {
this.x += this.vx * this.speed;
this.y += this.vy * this.speed;
},
toRadians: function(v) {
return v/180*Math.PI;
}
};
Notice I use the colon ':' instead of the '=' to assign values. Also, each element in the list ends with a ',' comma. Don't forget to put commas after functions as well!
Another problem with JSON is that it does not initialize a constructor. This means, you can't create objects that take in data from a constructor. Furthermore, you can't create multiple instances of the object, unless you make clones of it. In short, use this as a struct, or a quick object to get a job done. The above spaceship example is a poor use of JSON, as you can image it's better to keep it a formal object. A great example of JSON in action, is making Point objects:
var location = {x: 80, y: 80};
Then you have wrapped up several values into one package. Now, the identifier location can be used to access the inner content:
location.x = 120; location.y = 60;
And that is all to Object Notation!
By: Radnen