Variables
let myInt = 101; // Number (Integer)
let myFloat = 45.81; // Number (Float)
let positive = true; // Boolean
let message = "Hello World!"; // String
const PI = 3.14159; // Constant
let letter; // Declaration
letter = 'a'; // Initialization
Comments
// Comment on a single line
/*
Block comments
Everything in here will be
treated as a comment
*/
Arithmetic
let foo = 5;
foo++;
let bar = 10;
foo = foo + bar;
/*
+ : Addition - : Subtraction
* : Multiplication / : Division
% : Modulus Division
++ : Increase by 1 -- : Decrease by 1
*/
foo += 12; // Addition assignment operator
foo -= 35; // Subtraction assignment operator
Conditionals
let year = 2018;
if (year > 2018) {
message = "After 2018";
}
else if (year < 2018) {
message = "Before 2018";
}
else {
message = "The year is 2018!";
}
/*
== : Equal to (loose) != : Not Equal to
=== : Equal to (strict) !== : Not Equal to (strict)
> : Greater than < : Less than
>= : Greater or equal <= : Less or equal
*/
Loops
let foo = 0;
// While Loop
while (foo < 100) {
foo++;
}
let sum = 0;
// For Loop
for (let i = 0; i < 100; i++) {
sum += i; // adds all values from 0 to 99
}
Arrays
// Declares an array "points"
let points = [];
points[0] = 716;
points[1] = 482;
console.log(points[1]); // Prints 482
// Initialize at declaration
let grades = ['A', 'C', 'A', 'B'];
// Array length
let count = grades.length;
Functions
function isNegative(n) {
return n < 0;
}
let answer = isNegative(-5);
if (answer) {
console.log("Number is negative!");
}
// Arrow Function
const add = (a, b) => a + b;
Objects
let person = {
name: "Bob",
age: 30,
ssn: 123456789
};
// Access properties
console.log(person.name); // Prints "Bob"
console.log(person["age"]); // Prints 30
// Classes (ES6+)
class Car {
constructor(brand) {
this.carname = brand;
}
}
let myCar = new Car("Ford");
← Back to Home