Modern Javascript

source

types

JavaScript can be written between either the head or the body tags in a page of html. It is better to place it at the bottom of the body tags, so that the page can load before the script is read. This is fine for short scripts but the majority of the time we link to exterior files.

JavaScript has the following types:

typeexample
Number1,2,3,100,3.14
String"Hello, World!" "another string"
Booleantrue false
Nullexplicitly set with no value
Undefinednot yet defined
ObjectComplex data structures
Dates, Arrays, Literals etc
SymbolUsed with objects

Numbers

Variables are assigned with either var, let or const. var is the oldest way of initialising variables with let and const being more recent additions to the JavaScript syntax. The const variable can not be altered after initialisation where the var and the let variables can. The let initialised variables can also change type.

var x = 25;
const y = 100;
console.log(x, y); // 25 100

x = 30;
y = 125;
console.log(x, y); // 30 125

let z = 23;
console.log(z); // 23

z = "a new type";
console.log(z); // a new type
			

The browser devtools console is effectively a javascript shell, commands can be written directly into the console and they will run on the press of enter.

String

Strings have several methods accessible to them that will return information about the content of the string.

We can access individual characters within a string by using array notion

var str = "Hello, World!";
console.log(str[0]); // H
			

string members

We can access string object values members such as it"s length.

console.log(str.length) // 23
			

string functions

We can also call functions such as,

console.log(str.toUpperCase()); // HELLO, WORLD!
console.log(str.toLowerCase()); // hello, world!
			

concatenation

Strings can be concatenated using the + unary operator between string literals and variables containing strings.

var title = "the bloggers log";
var name = "mario";
var likes = 10;
var concat = "The site called " + title +
	" by " + name + " has " + likes + " likes";
console.log(concat);
	// The site called the bloggers log by mario has 10 likes
			

This can become a little unwieldy at times.

template strings

An alternative for longer string requirements is to use string templates.

var tmpl = `The site called ${title} by ${name} has ${likes} likes`;
console.log(tmpl);
	// The site called the bloggers log by mario has 10 likes
			

arrays

arrays are a subtype of the object, they can store any types, this is how they are instantiated.

let days = ["mon", "tues", "wed", "thur", "fri", "sat", "sun"];
console.log(days); // [ "mon", "tues", "wed", "thur", "fri", "sat", "sun" ]
console.log(days[2]); // wed