JavaScript Crash Course

 

An introduction to basic javascript syntax.

Declare variables using keywords let, const or var (unrecommended).

1
2
3
4
5
// let, const
let age = 30;
age = 31;
let num;
const name = 'peter';

Primary data types: Strings, Numbers, Boolean, null, undefined, Symbol

1
2
3
4
5
6
7
8
9
const name = 'john';
const age = 20;

const rating = 4.5;
const iscool = true;
const x = null;
const y = undefined;
let z;
console.log(typeof z);

String

1
2
3
4
// Template String
console.log(`My name is ${name} and I am ${age}`);
// Old style
console.log('My name is ' + name + ' and I am ' + age);

String manipulation

1
2
3
4
5
const s = 'Hello World';
console.log(s.length);
console.log(s.toUpperCase());
console.log(s.substring(0, 5).toLowerCase());
console.log(s.split(''));

Array

1
2
3
4
5
6
7
8
9
10
const numbers = new Array(1, 2, 3);
const fruits = ['apples', 'oranges', 'pears'];
// notice you can't reassign const variables
fruits[3] = 'grapes';
fruits.push('mangos');
fruits.unshift('strawberries');
fruits.pop();
console.log(fruits);
console.log(fruits.indexOf('oranges'));
console.log(Array.isArray(fruits));

Object literals

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
// Object literals
const person = {
firstName: 'John',
lastName: 'Snow',
age: 20,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 main st',
city: 'Boston',
state: 'MA'
}
};

person.email = 'john@gmail.com';

// pull things out
const { firstName, lastName, address: { city } } = person;

console.log(person.hobbies[1], person.address.city);
console.log(firstName, city)

Convert to JSON format

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
const todos = [
{
id: 1,
text: 'Take out trash',
isCompleted: true
},
{
id: 2,
text: 'Meeting with boss',
isCompleted: true
},
{
id: 3,
text: 'Dentist appt',
isCompleted: false
}
];

// console.log(todos[1].text);

// Convert to JSON
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);

Loop

1
2
3
4
5
6
7
8
9
// for loop
for(let i = 0; i < todos.length; i++) {
console.log(todos[i].text);
}

// simpler version
for(let todo of todos) {
console.log(todo.text)
}

High order array method: forEach, map, filter

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
// forEach
todos.forEach(function(todo) {
console.log(todo.text);
});

// map
const todoText = todos.map(function(todo) {
return todo.text;
});
console.log(todoText);

// filter
const todoCompleted = todos.filter(function(todo) {
return todo.isCompleted === true;
});
console.log(todoCompleted);

// combine filter and map
const todoCombine = todos
.filter(function(todo) {
return todo.isCompleted === true;
})
.map(function(todo) {
return todo.text;
});
console.log(todoCombine);

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
const x = 10;
const color = x > 10 ? 'red' : 'blue';
console.log(color);

switch (color) {
case 'red':
console.log('color is red');
break;
case 'blue':
console.log('color is blue');
break;
default:
console.log('color is NOT red or blue');
break;
}

Function definition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Function
function addNums(num1, num2 = 1) {
return num1 + num2;
}

// Arrow function
const addNums2 = (num1, num2 = 1) => {
return num1 + num2;
};
console.log(addNums2(4));

const addNums3 = (num1 = 1, num2 = 1) => num1 + num2;
console.log(addNums3(2, 2));

const addNums4 = num1 => num1 + 5;
console.log(addNums4(3));

Class definition

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
// Constructor function

function Person(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}

// use prototype
Person.prototype.getBirthYear = function() {
return this.dob.getFullYear();
};
Person.prototype.getFullName = function() {
return `${this.firstName} ${this.lastName}`;
};

// Class (prefered way do the same thing as above)
class Person {
constructor(firstName, lastName, dob) {
this.firstName = firstName;
this.lastName = lastName;
this.dob = new Date(dob);
}

getBirthYear() {
return this.dob.getFullYear();
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
}

// Instantiate object
const person1 = new Person('John', 'Snow', '4-3-1980');

console.log(person1.getBirthYear());
console.log(person1.getFullName());
console.log(person1);

DOM (document object model)

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
// Single element
console.log(document.getElementById('my-form'));
console.log(document.querySelector('.container'));

// Multiple element
console.log(document.querySelectorAll('.item')); // recommend
console.log(document.getElementsByClassName('item'));

//
const ul = document.querySelector('.items');
ul.lastElementChild.remove();
ul.firstElementChild.textContent = 'Hello';
ul.children[1].innerText = 'Brad';

const btn = document.querySelector('.btn');
btn.style.background = 'red';

Events

1
2
3
4
5
6
7
8
9
const btn = document.querySelector('.btn');

btn.addEventListener('click', e => {
e.preventDefault();
document.querySelector('#my-form').style.background = '#ccc';
document.querySelector('body').classList.add('bg-dark');
document.querySelector('.items').lastElementChild.innerHTML =
'<h1>Hello</h1>';
});

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
const myForm = document.querySelector('#my-form');
const nameInput = document.querySelector('#name');
const emailInput = document.querySelector('#email');
const msg = document.querySelector('.msg');
const userList = document.querySelector('#users');

myForm.addEventListener('submit', onSubmit);

function onSubmit(e) {
e.preventDefault();
if (nameInput.value === '' || emailInput.value === '') {
msg.classList.add('error');
msg.innerHTML = 'Please enter all fields';

setTimeout(() => msg.remove(), 3000);
} else {
const li = document.createElement('li');
li.appendChild(
document.createTextNode(`${nameInput.value} : ${emailInput.value}`)
);

userList.appendChild(li);

// Clear fields
nameInput.value = '';
emailInput.value = '';
}
}

Reference

Javascript Crash Course for Beginners