Chapter 1: Types and variables

Javascript only has a couple of types that you really need to use. They are:

  • Number
  • String
  • Boolean
  • Function
  • Array
  • Object Literal

Comments

Add comments in your code like most other languages using // or /**/.

// a one line comment
 
/* this is a longer, 
   multi-line comment
 */
 
/* You can't, however, /* nest comments */ SyntaxError */

Declaring variables

When you want to instantiate a variable, you should initiate them by using the 'var' keyword.

var number = 123; // this is a Number
var string = "hello"; // this is a String
var condition = true; // true or false
var doSomething = function () {}; // this is a function
var object = {}; // this is an object
var idk; // undefined var, you can set it later

Variables can be any type. For example, if you decide that you want the "var number" to be a String after all, you can do so at any time. This is called dynamic typing, as opposed to static typing.

Note: if you forget to write "var", the variable you declare will be global. More on scopes later!

Number and String

Here are some examples of playing with Number and Strings:

// Cash is a number
var cash = 10;

// It could also be a string.
// Note: you can use '' or "", it doesn't matter
cash = '$10'; 
cash = "I have 10 dollars! I'm rich!!"; 

// Strings have methods and properties
cash = "$10";
console.log(cash.length); // Output: 3

// Numbers also have methods! For example you can use .toString()
cash = 10;
cash = cash.toString(); 
console.log(cash); // Output: "10"

Operators between Number and String

Using numbers and string should be pretty straight forward. Note that you can use operators on numbers and strings. Keep in mind that using + on Numbers and Strings will always result in strings. Other operators between Numbers and Strings result in Numbers. 

// using + on a String and Number results in a string
cash = '$' + 10 + "," + 21;
console.log(cash); // Output: "$10,21"

// using * between String and Number results in a Number
cash = 2 * "10";
console.log(cash); // Output: 20

// as long as the String is parsable as Numbers!
cash = "$" * 10;
console.log(cash); // Output: NaN, aka Not A Number

Arrays

Arrays are data structures in which you can hold sequential data. It's simply a row of data, which can be Numbers, Strings, Booleans etc. Basically anything. Arrays can be instantiated using square brackets [].

var array = []; // emtpy array
array = [1, 2, 3]; // array with data
array = [1, 'hello', true]; // arrays can hold any data

Accessing the data

To access the array data, you use [] with an index. The index starts at 0.

var array = [300, "hello", true];
// get the first data in array, starts with 0
console.log(array[0]); // Output: 300
// get the 2nd data in array
console.log(array[1]); // Output: "hello"

// or any other index
var index = 2;
console.log(array[2]); // Output: true

// an out of bounds index will not result in an error, instead will return undefined
console.log(array[3]); // Output: undefined

// Use the length property to see how many elemnents the array has
console.log(array.length); // Output: 3

Editing the data

You can edit arrays easily. Just access the the element and assign something new:

var array = [1, 2, 3];
// change the 2nd element
array[1] = 3;
console.log(array); // Output: [1, 3, 3];

Add new elements to the end of the array using push(). To remove the last element, use pop(). 

var array = [1, 2, 3];
// push adds an element
array.push(4);
console.log(array); // Output: [1, 2, 3, 4];

// pop removes the last element and returns it
var lastElement = array.pop();
console.log(lastElement); // Output: 4
console.log(array); // Output: [1, 2, 3]

Object Literal

The object literal is another data structure. They hold data by key-value pairs. This means you give each element a name (key) and assign a value to it. Each key-value pair is separated by a comma.

They are instantiated by curly braces {}. Example:

// an empty object literal
var cat = {};

// objects can save data as key-value pairs
cat = {
  age: 5,
  name: 'Lucky Kat'
};

Accessing the data

There are a number of ways to access data. You can use the dot operator . to access an element by name. That same operator can also be used to edit or assign new values to the object literal.

// access data or add new using . operator
var cat = {
  age: 5,
  name: "Lucky Kat"
};

// access the data with .
console.log(cat.age); // Output: 5

// or edit data 
cat.name = 'Nom Cat';

// or assign data
console.log(cat.meow); // Output: undefined
cat.meow = 'meow';
console.log(cat.meow); // Output: "meow"

Another way of accessing data is using the square brackets []. It's similar to accessing data with arrays, but instead of Number inputs, you use Strings as input to get to the data.

// access data using [] operator
var cat = {
  age: 5,
  name: "Lucky Kat"
};

// access the data with .
console.log(cat["age"]); // Output: 5

Nesting object literals

Object literals can hold any data, that includes Arrays and Object Literals themselves. This can turn object literals into pretty complicated forms. For example:

var dad = {
  name: "Homer",
  age: 36,
  wife: {
    name: "Marge",
    age: 34
  },
  children: [
    { // <-- look closely! this is an array of object literals!
      name: "Bart",
      age: 10
    },
    {
      name: "Lisa",
      age: 8
    },
    {
      name: "Maggie",
      age: 1
    }
  ] // the array ends here
};

// Exercise: how would you access Maggie's age?

Comparison and truthy/falsy

When comparing values in Javascript, you can use == or ===. The latter looks a little strange and is an unusual JavaScript feature. Always use ===. You can read more about this at https://developer.mozilla.org/en-US/docs/Web/JavaScript/Equality_comparisons_and_sameness

var data = 2 + 2;
if (data === 4) { // true!
  // do stuff here
}

if ("0" == 0) { // also true!
  // whereas "0" === 0 equals false
}

Another thing to note: only Numbers, Strings and Booleans are compared by content. Whereas other types are compared by their referene.

var cat = {
  name: "Nom Cat"
};

// Strings are compared by content
if (cat.name === "Nom Cat") {
  // true!
}

// despite the contents being exactly the same, these objects are different
var sameCat = {
  name: "Nom Cat"
};

if (cat === sameCat) {
  // false!
}

// this holds a reference to the first Object Literal, so this is the same! 
var anotherCat = cat;
if (cat === anotherCat) {
  // these 2 cats point to the same Object Literal
}

Another unusual JavaScript feature (but very useful) is the concept of falsiness. Whereas in most languages it is required to pass a true/false (Boolean) to if-statements, it is sufficient in JavaScript to be "truth-y" or "falsy". The following are considered falsy:

  • false
  • undefined
  • null
  • 0
  • NaN
  • an empty string ('' or "")

Anything else is considered to be truthy and could pass if-statements. Some examples:

var objLiteral = {};
if (objLiteral) { // truthy!
  // will run this
}

var idk;
if (idk) { // idk is undefined
  // falsy!
}
if (!idk) { // "not" idk becomes truthy!
  // truthy!
}