JavaScript syntax quick reference guide
If you know the basics of JavaScript, you can skip this section. Here is a quick overview of JavaScript:
- Use the keyword var to define a variable:
var myAge = 31;
- Use // for inline comments and /* */ for multiline comments:
// this is an inline comment /* this is a multi-line comment */
- Conditional statements:
if (myAge > 29) { console.log("I am not in my twenties anymore!"); } else { console.log("I am still in my twenties!"); }
- Defining a function:
function nameOfMyFunction(argument1, argument2) { console.log(argument1, argument2); }
- Executing a function:
nameOfMyFunction("First Value", "Second Value");
- A function can also behave as a class and have methods, properties, and instances. Properties are accessed through the keyword this:
function Car(maxSpeed) { this.maxSpeed = maxSpeed; this.currentSpeed = 0; }
- The standard way to create a prototyped method for a function in JavaScript is by using the property prototype:
Car.prototype.brake = function() { if (this.currentSpeed > 0) { this.currentSpeed -= 5; } }; Car.prototype.accelerate = function() { if (this.currentSpeed < this.maxSpeed) { this.currentSpeed += 5; } };
- To create an instance of a class in JavaScript, use the keyword new:
var car = new Car(100); car.accelerate(); car.accelerate(); car.brake();
- Arrays and objects:
var myArray = []; var myObject = {};
- Callbacks in JavaScript:
var friends = ["Karalyn", "Patrik", "Bernardo"]; friends.forEach(function (name, index) { console.log(index + 1, name); // 1 Karalyn, 2 Patrik, 3 Bernardo });
A callback in this example is an anonymous function that is passed to another function as a parameter, so it is called (or executed) inside the other function. As you can see in the preceding example, the forEach array method expects a callback function. It executes the provided callback once for each element in the array. It is very common to find asynchronous functions/methods that expect callbacks in JavaScript.
If you want to know more about JavaScript syntax and features, we recommend the Mozilla Developer Network website at https://developer.mozilla.org/en-US/docs/Web/JavaScript.