JavaScript Basics
This primer introduces the fundamentals of the JavaScript language.
Contents
Control Flow
JavaScript uses C-like syntax.
// function calls
myFunction();
// return from function
return "foo";
// if statements (multi-line)
if (foo) {
// do something
}
else if (bar) {
// do something else
}
else {
// do another thing
}
// if statements (single-line)
if (foo) doSomething();
else if (bar) doSomethingElse();
else doAnotherThing();
// while loops
while (foo) {
// do something
}
// do...while loops
do {
// do something
} while (foo);
// for loops
for (let i = 0; i < 10; i++) {
// do something ten times
}
// exceptions
try {
// do something
throw new Error("my error message"); // throw an exception
}
catch (err) {
// run this code after an error is thrown
}
finally {
// run this code after try or catch completes
}
Operators
JavaScript uses C-like operators, except for equality, which has special rules.
// assignment
a = b;
// strict equality
if ("1" === 1) // false
if ("1" !== 1) // true
// loose equality (don't use—it has strange type conversion rules)
if ("1" == 1) // true
if ("1" != 1) // false
// less than, greater than
if (1 < 2) // true
if (1 <= 2) // true
if (1 > 2) // false
if (1 >= 2) // false
// arithmetic
1 + 2 // 3
1 - 2 // -1
1 * 2 // 2
1 / 2 // 0.5
// string concatenation
"1" + "2" // "12"
1 + "2" // "12"
"1" + 2 // "12"
// ternary operator
c = (1 < 2) ? "yes" : "no";
// ternary operator is equivalent to:
if (1 < 2) {
c = "yes";
}
else {
c = "no";
}
Variables
JavaScript has two primary ways to declare variables:
const myVar = "foo";
let myVar = "foo";
const
means the variable can’t be modified after it’s created. (Except for objects and arrays. See those sections for details.)
let
means the variable can be modified after it’s created.
Most people use const
by default, and only use let
when a variable needs to be modified. This tends to make code easier to reason about, because you don’t have to worry about how variables might change.
Primitives
JavaScript is dynamically typed, which means any variable can hold any type. The following primitive types are available:
// floating-point numbers (JavaScript doesn't have integers)
const a = 3.14;
const b = 4;
// strings
const c = "I'm a string";
const d = 'I"m also a string';
const e = `I use backticks to interpolate ${variable}s`;
const f = "Any string can use backslash to escape \"quotes\" and add newlines.\n";
// booleans
const g = true;
const h = false;
// undefined
let i; // i defaults to 'undefined'
const j = undefined;
(i === j) // true
// null
const k = null;
// undefined vs. null
// 'undefined' and 'null' are two different ways of saying "no data". JavaScript is weird.
(undefined === undefined) // true
(null === null) // true
(undefined === null) // false
(undefined == null) // true -- but don't use the loose equality operator
Functions
Use the function
keyword to create a function, parentheses to call it, and the return
keyword to return a value. Functions can be declared after they’re used.
const result = foo("foo", "bar", "baz") // outputs "foobarbaz"
console.log(result); // outputs "42"
function foo(a, b, c) {
console.log(a + b + c);
return 42;
}
Objects
Objects consist of name/value pairs. The name is a string and the value can be anything, including another object:
const myObject = {
a: 1,
b: "foo",
c: true,
d: {
anotherObject: true,
},
};
To get a value out of an object, you can use a dot and hardcode the name, or use brackets containing any expression:
const myObject = {
a: "foo",
b: "bar",
};
const e = myObject.a; // e contains "foo"
const f = myObject["b"]; // f contains "bar"
const g = "b";
const h = myObject[g]; // h contains "bar"
Object variables contain references. Assigning an object to another variable doesn't copy the object, just the reference. If the object is changed in one place, it will also change in the other.
// create an object
const a = {
foo: "bar",
}
console.log(a); // { foo: "bar" }
// copy the object reference
const b = a;
// change the object using the new reference
b.foo = "changed";
console.log(b); // { foo: "changed" }
// a also sees the change
console.log(a); // { foo: "changed" }
Because variables store the object reference, not the object itself, making an object variable const
only prevents you from changing the reference. It doesn’t prevent you from changing the underlying object being referenced.
const myObject = {
foo: "bar";
}
// throws exception--you can't change myObject because it's const
myObject = "something else";
// works fine, because the myObject variable isn’t changing, just the object it references
myObject.foo = "something else";
console.log(myObject); // { foo: "something else" }
Arrays
Arrays are a special kind of object. Their property names count up from zero.
const myArray = [ "foo", "bar", "baz" ];
const a = myArray[0]; // a contains "foo"
const b = [ 1, true, "foo" ]; // you can mix data types
Like objects, arrays are stored as references. Assigning an array to another variable doesn't copy the object, just the reference. If the array is changed in one place, it will also change in the other.
// create an array
const a = [ "foo" ];
console.log(a); // [ "foo" ]
// copy the array reference
const b = a;
// change the array using the new reference
b[0] = "changed";
console.log(b); // [ "changed" ]
// a also sees the change
console.log(a); // [ "changed" ]
Also like objects, const
array variables don’t prevent the underlying array from being changed.
const myArray = [ "foo" ];
// throws exception--you can't change myArray because it's const
myArray = "something else";
// works fine, because the myArray variable isn’t changing, just the array it references
myArray[0] = "something else";
console.log(myArray); // [ "something else" ]
Classes
Use the class
keyword to create a class and the new
keyword to instantiate it. Classes can be declared after they’re used. Methods work like function calls.
const a = new MyClass(); // instantiate
a.myMethod(); // call myMethod()
class MyClass {
// instance variables don't need to be declared in JavaScript
constructor() { // optional
// initialization code
}
myMethod() {
// method code
}
}
The this
keyword refers to the current object. It has some strange rules that shouldn’t be an issue in this course. If you’re curious, you can learn more about them in this video.