JavaScript

A quick introduction to the best high-level, dynamic, weakly typed, prototype-based, multi-paradigm, and interpreted programming language!

JavaScript… A Brief History

  • One of 3 core technologies of the World Wide Web, all browsers have a built-in JavaScript engine.
  • Brendan Eich wrote JavaScript in 10 days in 1995.
  • Netscape Communications hired Eich in 1995, to create a scripting language to complement Java.
  • EMCA International published the first edition of the ECMA-262 standard in June 1997.
  • The language has grown in popularity

To start playing around with JavaScript, open the browser console (F12)!

Basics

Comments

// Single-line comment

/* Multi
   Line
   Comment */

Arithmetic Operators

Operation Result
x + y Add both numbers
x - y Subtract y from x
x * y Multiply both numbers
x / y Divide x by y
x % y The remainder of dividing x by y

Variables

// Declaring a variable
let identifier = 35;

var myVar = 20;
const myConst = 20; // Constant
let myLet = 20;

Types

// Number
var age = 18;
// String
var lastName = "Smith";                      
// Boolean
var adult = true;
// Array
var types = [1, 1, true];
// Object
var name = {first:"John", last:"Doe"};    

Comparison Operators

Operation Result
x < y Returns true if x is less than y
x > y Returns true if x is greater than y
x <= y Returns true if x is less than y
x >= y Returns true if x is less than y

Equality Operators

Operation Result
x == y Check if the values are equal
x === y Check if value and type are equal
x != y Check if the values are not equal
x !== y Check if value and type are not equal

Type Coercion

  • Not unique to JavaScript and found in other languages such as PHP
    • == and != compare with type coercion
    • === and !== compare without type coercion
  • 3 is a number, but “3” is a string
  • You should almost always use ===
"3" == 3  // true
"3" === 3 // false

Boolean

Operation Result
true Always true
false Always false
A && B True if both A and B are true
```A
!A The opposite of A

Conditionals

if/else

if (5 < 2) {
	console.log ("Ummm...");
} else {
	console.log ("Suprise!?");
}

else if

if (5 < 2) {
	console.log (Ummm...);
} else if (5 >= 2) {
	console.log (Suprise!?);
} else {
	console.log (Whaaaat???);
}

Loops

While Loops

const arr = [23, 45, 78];
let i = 0;

while (i < arr.length) {
	console.log (arr[i]);
	i+= 1;
}

For Loops

for (let i = 0; i < 10; i++) {
	console.log (index  + i);
}

Functions

Declarations & Calls

function add (num1, num2) {
	return num1 + num2;
}

add (3, 4); // === 7

Methods

var str = "Hello World!";
str.length; // 12
str.indexOf(!) // 11

Math.floor(Math.random() * 10);

Objects

var object = {key: "value"};

object.key;
object["string key"];

Arrays

Actually just JS objects!

const object = {key: "value"};

const array = ["abc", "xyz"];
const arrayObject = {0: "abc", 1: "xyz"};

Resources