Skip to content

Instantly share code, notes, and snippets.

@potikanond
Last active January 14, 2020 06:25
Show Gist options
  • Save potikanond/6fbc731c8e87e4d5c65ea9b925d917ce to your computer and use it in GitHub Desktop.
Save potikanond/6fbc731c8e87e4d5c65ea9b925d917ce to your computer and use it in GitHub Desktop.
JavaScript Tutorial 2020

JavaScript Crash Course

Use Console tab for single line instruction. Executing single instruction at a time.

// Warning
alert('Hello');

// Confirm?
let val = confirm("Do you want to continue ?");
console.log('Confirm : '+ val);

let name = prompt("Enter your name:", "Enter your name here!");
console.log('Name : ' + name);

Use shift+Enter to add more line of instructions

alert('Hello'); // shift+Enter
alert('Dome Potikanond');

Instead, use the Source tab and the Snippet menu to create script (*.js) and use Ctrl+Enter to run the script.

JavaScript kewords: https://developer.mozilla.org/en-US/docs/Web/JavaScript

Data Types

  • String: "This is string", 'This is also a string'
  • Numbers: 123
  • Boolean: true, false
  • Null: nothing (object)
  • Undefined: no value (primitive)

In console, you can type these instructions

2+3;
alert(2+3);
typeof(23);
typeof('This is a string')
type(true);

Note: To clear the console, press Ctrl+L. There are 3 ways type of console output, i.e. log, error, and warning.

console.log('Hello World');
console.error('This is an error');  // red
console.warn('This is a warning');  // yellow

Variables

How can we remember value of data? There are 3 keywords relating to defining a variable.

  • var : globally scope, due to hoisting (do not recommend)
  • let : locally scope
  • const : unless you need to reassign the value, try using this

There are primitive data types: String, Number, Boolean, null, undefined

const pi = Math.PI;
console.log(pi);
console.log(pi.toFixed(2));

let name = 'John Doe';
name = prompt('What is your name?');
console.log('Your name is '+ name);

// use back-tick `...` to quote with "template literals"
console.log(`Again, your name is ${name + '...'}`);

There are primitive data types: String, Number, Boolean, null, undefined

const name = 'John';
const height = 178;
const weight = 68.5;  // also a number
const isCool = true;
const x = null;       // empty value
const y = undefined
let z;                // also undefined
console.log(typeof isCool);
console.log(typeof z);

The name can only contains letters, numbers, '$', and '_' (underscore). No other symbols are valid for naming.

Camel casing naming: first word are not capitalized!!! e.g. firstName, theFinalScore, ...

Note: To clear variables and cache, right-click on reload button and choose Empty cache and Hard reload or Ctrl+R.

Strings

Finding length of string using length property.

// Calculate available characters for tweet.
let max_length = 140;
let tweet = prompt("Enter your tweet:");
alert('You have written '+ tweet.length + ' characters, you have ' + (max_length-tweet.length) + ' characters left.' );

We can use slice method to get part of string.

let name = 'This is a good day to learn JS';
console.log( name.slice(0,4) );
console.log( name.slice(5,name.length) );

To cut your tweet input to only 30 characters.

let max_length = 40;
let tweet = prompt("Enter your tweet:");
alert('You have written '+ tweet.length + ' characters, you have ' + (max_length-tweet.length) + ' characters left.' + '\n\n' + tweet.slice(0,max_length) );

or

alert(prompt("Compose your tweet (max 40 characters):").slice(0,40));

Use .toUpperCase() and .toLowerCase() to change case of string.

// A script to get capitalized fist name
let name = prompt('What is your name?');
let firstChar = name.slice(0,1);
firstChar = firstChar.toUpperCase();
name = firstChar + name.slice(1,name.length).toLowerCase();
alert('Hello ' + name);

We can use the .split() method to split string into a list of list of multiple elements. Try this code.

let str1 = "Johny Trump";
console.log(str1.split());
console.log(str1.split(' '));
console.log(str1.split(''));

Arithmetic

Traditional math operators (+,-,*,/,%) and precedences work the same way in JavaScript as in most computer languages.

let dogAge = prompt('enter dog age:');
let humanAge = (dogAge-2) * 4 + 21;
alert(dogAge + ' yrs old dog is equal to ' + humanAge + ' yrs old human.');

The increment/decrement, i.e. ++ and --, as well as those compounded assignments, i.e. += -= *= ..., also work the same way as in C++.

Arrays

JavaScript is zero-based index array. To define an array, we can use assignement (=) or the new keyword.

// using constructor
const nums = new Array(1,2,3,4,5,6);
console.log(nums);
console.log(typeof(nums));

// using assignment
let arr = [1,2,3,4,5,6];
console.log(arr);
console.log(typeof(arr));

const fruits = ['apples', 'oranges', 'mango', 10, 14.5, true, [1,2,3]];
console.log(fruits);
fruits[6] = 'watermelon';   // add new item to the end of array
console.log(fruits);
fruits.push('end1');        // put an item to the end
fruits.unshift('start');    // put an item to the start
console.log(fruits);
fruits.pop(); fruits.pop()  // pop 2 items out
console.log(fruits);

console.log("'hello' is array?: "+ Array.isArray('hello'))
console.log('fruit is array?: ' + Array.isArray(fruits));
console.log(fruits.indexOf('mango'));   // find index of an item

Be careful when using assignment (=) because the new variable will share the same memory space due to the shallow copy.

let a1 = [1,2,3,4,5,6];
let a2 = a1;
a2[1] = '2222';
console.log(a2);
console.log(a1);

let a3 = a2.slice(0,3);
a3[2] = 333.333;
console.log(a3);
console.log(a2);

Array has some useful properties and methods.

let guestList = ['Angela','Jack','Pan','James','Lara','Jason'];

console.log(guestList.length);
console.log(guestList.includes('Dome'));
console.log(guestList.includes('Jack'));

Object Literals

It is possible to create object using the { ... }. Object contains key:value pairs of data.

const person = {
  fname: 'Dome',
  lname: 'Potikanond',
  age: 42,
  hobbies: ['music', 'movies', 'sports'],
  address: {
    street: '239 Huaykaew rd.',
    city: 'Chiang Mai',
    country: 'Thailand'
  }
}
console.log(person);
console.log(person.fname + '(' + person.age + ')');
console.log(person.hobbies[1]);
console.log(person.address.street);

We can populate data inside an object to external variables using destructuring process.

// Destructuring - create variables from object properties
const { fname, lname } = person;
console.log(fname+' '+lname);
const { address: {city} } = person;
console.log(`${fname} ${lname} (${city})`);

To add new property, we use .key_name pattern.

// add new property
person.email = '[email protected]';
console.log(person);

We can create an array of objects as shown in the example below.

// Array of objects
const todos = [
  {
    id: 1,
    text: 'Meeting with advisor',
    isCompleted: true
  },
  {
    id: 2,
    text: 'Shopping for food',
    isCompleted: false
  },
  {
    id: 3,
    text: 'Do web dev homework',
    isCompleted: true
  },
]
console.log(todos[1].text);

JSON - JavaScript Object Notation

A format for data interchange between client/server. We can create JSON string out of JavaScript object using JSON.stringify() static method. To get back JavaScript object from JSON string, we use JSON.parse() static method.

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

let parseTodos = JSON.parse(todoJSON);
console.log(parseTodos)

Random number generation

Math.random() generate a random float between [0,1). To get random number between [1,6]

let n = Math.random();
console.log(Math.floor(n)*6+1);

Control statements

if/else

prompt('What is your name?');
prompt('What is their name?');

let loveScore = Math.random() * 100;
loveScore = Math.floor(loveScore)+1
console.log('Your love score: ' + loveScore + '%')
if (loveScore === 100) {
  console.log('You are true love!!!');
} else if (loveScore>=85) {
  console.log('You are meant to be... definitely... quite sure!')
} else if (loveScore>=50 && loveScore<85) {
  console.log('You are meant to be... probably!')
} else {
  console.log('You may NOT be a good couple.');
}

Comparators and Equality

  • === : is equal to (with the same data type)
  • == : is equal to (without checking data type)
  • !== : is NOT equal to
  • != : is NOT equal to
let a=1,b='1';
console.log(typeof(a));
console.log(typeof(b));

if (a === b)
    console.log('yes, a === b');

if (a == b)
    console.log('yes, a == b');

if (a !== b)
    console.log('no, a !== b');

if (a != b)
    console.log('no, a != b');

When a=1,b='1', the output of comparisons will be:

number
string
yes, a == b
no, a !== b

If we change a = 1, b = 1.0, the result will be:

number
number
yes, a === b
yes, a == b

If we change a = 1, b = '2', the result will be:

number
string
no, a !== b
no, a != b

Loop

JavaScript has for-loop and while-loop.

let i = 10;
let str = '';
while (i>0) {
  str += `${i} `;
  i--;
}
console.log(str);

for (let i=0; i<todos.length; i++) {
  console.log(`${i+1}. ${todos[i].text}`);
}

There is another way of using for-loop with array.

// for each 'todo' in 'todos' array do something
for (let todo of todos) {
  console.log(todo.id + ' - ' + todo.text);
}

High Order Functions

JavaScript has a couple of useful array methods that take other function as argument.

  • .forEach() : on each element apply function, does not create new array.
  • .map() : create new array from input array.
  • .filter() : create new array by filtering input array with speciied conditions.
// High-order loop: forEach, map, filter
todos.forEach( function(todo,index) {           // forEach
  console.log(`${index+1}: ${todo.text}`);
});

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

const todoCompleted = todos.filter( todo => {   // Filter (and then Map)
  return todo.isCompleted === true;
}).map( todo => { 
  return todo.text; 
});
console.log(todoCompleted);

Functions

Packing series of instructions into a block of code and give it a name.

// function definition
function getMilk(bottles=1) {
  console.log('go to the supermarket#1');
  console.log('buy ' + bottles + ' bottle(s) of milk');
  let cost = bottles * 1.5;
  console.log('pay $'+ cost +', go back home');
  console.log('put the milk in the refrigerator');
}

// calling the function
getMilk();

You can also use ES6 style arrow function to define your function.

getMilk2 = (bottles=1)=>{
  console.log('go to the supermarket #2');
  console.log('buy ' + bottles + ' bottle(s) of milk');
  let cost = bottles * 1.5;
  console.log('pay $'+ cost +', go back home');
  console.log('put the milk in the refrigerator');
  console.error('This is error msg');
}

getMilkByMoney = (money=0.0)=>{
  console.log('go to the supermarket #2');
  let numberOfBottles = Math.floor(money/1.5);
  console.log('buy ' + numberOfBottles + ' bottle(s) of milk');
}

To get return value from function, we can use return keyword. The following function return the change money from buying milk.

function getMilkByMoney2(money=0.0, costPerBottle) {
  console.log('go to the supermarket #2 with $' + money);
  console.log('the milk cost $' + costPerBottle + '/bottle')
  console.log('you can buy ' + calculateBottles(money, costPerBottle) + ' bottle(s) of milk');
  return calculateChange(money, costPerBottle);
}

function calculateBottles(money=0.0, costPerBottle) {
  let numberOfBottles = Math.floor(money/costPerBottle);
  return numberOfBottles;
}

function calculateChange(money=0.0, costPerBottle) {
    return money%costPerBottle;
}

console.log('You get $'+ getMilkByMoney2(20,3) + ' change.');

You will get the output as shown below:

go to the supermarket #2 with $20
the milk cost $3/bottle
you can buy 6 bottle(s) of milk
You get $2 change.

Fizzbuzz program

A couting program:

1 2 Fizz 4 Buzz Fizz 7 8 Fizz Buzz 11 Fizz 13 14 FizzBuzz ... 

Use .push() to add element to the end of a list and use .pop() to remove an item at the end of array.

let output = [];
let count = 1;

fizzBuzz = ()=> {
    
    if (count%3 === 0 && count%5 === 0) {
        output.push('FizzBuzz');
    } else if (count%3 === 0) {
        output.push('Fizz');
    } else if (count%5 === 0) {
        output.push('Buzz');
    } else {
        output.push(count);
    }
    count++;
    console.log(output);
}

fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();
fizzBuzz();

While Loops

Now we can do Fizzbuzz process multiple times using while.

let output = [];
let count = 1;
while (count<40) {

  if (count%3 === 0 && count%5 === 0) {
      output.push('FizzBuzz');
  } else if (count%3 === 0) {
      output.push('Fizz');
  } else if (count%5 === 0) {
      output.push('Buzz');
  } else {
      output.push(count);
  }
  count++;
}

console.log(output);

For Loops

We can also program Fizzbuzz using for as well. This time we count backward.

let output = [];
for (let count=50; count>0; count--) {

  if (count%3 === 0 && count%5 === 0) {
      output.push('FizzBuzz');
  } else if (count%3 === 0) {
      output.push('Fizz');
  } else if (count%5 === 0) {
      output.push('Buzz');
  } else {
      output.push(count);
  }
}

console.log(output);

Let's create the fibonacci(n) function that return a list of fibonacci numbers up to the nth location.

function fibonacciGenerator (n) {
  let output=[]
  for (let i=0; i<n; i++) {
    if (i===0)
      output.push(0);
    else if (i===1)
      output.push(1);
    else if (i>1)
      output.push(output[i-1]+output[i-2]);
  }

  //Return an array of fibonacci numbers.
  return output;
}
/* alert('Hello World'); */
console.log('Hello World');
console.error('This is an error'); // red
console.warn('This is a warning'); // yellow
// Variable: var, let, const
// var - globally scope, due to hoisting (do not recommended)
// let - locally scope
// const - constant (use this unless you need to reassign the value)
let age = 30;
age = 31;
console.log(age);
age = '45';
console.log(age);
const age2 = 30;
// age2++;
console.log(age2)
// Data type: primitive
// primitive types: String, Number, Boolean, null, undefined
const name = 'John';
const height = 178;
const weight = 68.5; // also a number
const isCool = true;
const x = null; // empty value
const y = undefined
let z; // also undefined
console.log(typeof isCool);
console.log(typeof z);
// String
console.log('My name is ' + name); // simple concatenation
console.log(`My name is also ${name}`); // template literals using 'back tick'
const hello = `My name is here is again also ${name}`
console.log(hello);
console.log(hello.length); // length property
console.log(hello.toUpperCase()); // toUpperCase() method
console.log(hello.substring(3,3+4).toUpperCase()); // from index=3 to 7 (exclusive)
console.log(hello.split(''));
console.log(hello.toUpperCase().split(' '));
// Arrays - zero-based index
const nums = new Array(1,2,3,4,5,6); // using constructor
console.log(nums);
const fruits = ['apples', 'oranges', 'mango', 10, 14.5, true, [1,2,3]];
console.log(fruits);
fruits[6] = 'watermelon'; // add new item to the end of array
console.log(fruits);
fruits.push('end1'); // put an item to the end
fruits.unshift('start'); // put an item to the start
console.log(fruits);
fruits.pop(); fruits.pop() // pop 2 items out
console.log(fruits);
console.log("'hello' is array?: "+ Array.isArray('hello'))
console.log('fruit is array?: ' + Array.isArray(fruits));
console.log(fruits.indexOf('mango')); // find index of an item
// Object Literals - key:vaue pairs
const person = {
fname: 'Dome',
lname: 'Potikanond',
age: 42,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '239 Huaykaew rd.',
city: 'Chiang Mai',
country: 'Thailand'
}
}
console.log(person);
console.log(person.fname + '(' + person.age + ')');
console.log(person.hobbies[1]);
console.log(person.address.street);
// Destructuring - create variables from object properties
const { fname, lname } = person;
console.log(fname+' '+lname);
const { address: {city} } = person;
console.log(`${fname} ${lname} (${city})`);
// add new property
person.email = '[email protected]';
console.log(person);
// Array of objects
const todos = [
{
id: 1,
text: 'Meeting with advisor',
isCompleted: true
},
{
id: 2,
text: 'Shopping for food',
isCompleted: false
},
{
id: 3,
text: 'Do web dev homework',
isCompleted: true
},
]
console.log(todos[1].text);
// JSON - a format for data interchange between client/server
// https://www.freeformatter.com/json-formatter.html (compare JS Object and JSON)
const todoJSON = JSON.stringify(todos);
console.log(todoJSON);
// Loop
let i = 10;
let str = '';
while (i>0) {
str += `${i} `;
i--;
}
console.log(str);
for (let i=0; i<todos.length; i++) {
console.log(`${i+1}. ${todos[i].text}`);
}
for (let todo of todos) { // todo variable could be anything
console.log(todo.id + ' - ' + todo.text);
}
// High-order loop: forEach, map, filter
todos.forEach( function(todo,index) { // forEach
console.log(`${index+1}: ${todo.text}`);
});
const todoText = todos.map( todo => { // Map
return todo.text;
});
console.log(todoText);
const todoCompleted = todos.filter( todo => { // Filter (and then Map)
return todo.isCompleted === true;
}).map( todo => {
return todo.text;
});
console.log(todoCompleted);
// Conditionals - for the most part, they are similar to C++
// ==, ===, && (ampersand), ||
const a = '10';
if (a == 10) { console.log('a == 10'); } // compare translated value
if (a === 10) { console.log('a === 10'); } // compare value and type
else { console.log('a !== 10');}
// Assign a variable based on the condition
let b;
const c = (b === undefined) ? 0:b;
console.log(c);
// Switch-case
const color = undefined;
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 and blue');
}
// Function
function addNums(num1=1, num2=1) {
return num1+num2;
}
console.log(addNums()); // NaN - Not a Number if no default params are not set
const addNums2 = (num1=1, num2=1) => num2+num1;
console.log(addNums2(5,5));
const addFive = num1 => num1+5;
console.log(addFive(10));
// this keyword
// OOP <ES5-2016> - constructive function
function Person(firstName, lastName, dob) {
// properties
this.fname = firstName;
this.lname = lastName;
// this.dob = dob;
this.dob = (dob === undefined)? new Date(): new Date(dob);
// methods - listed as properties in the object (NOT in prototype)
/* this.getBirthYear = function () { return this.dob.getFullYear(); }
this.getFullName = function() { return `${this.fname} ${this.lname}`; } */
}
// add prototype function
Person.prototype.getBirthYear = function() {
return this.dob.getFullYear();
}
Person.prototype.getFullName = function() {
return `${this.fname} ${this.lname}`;
}
// Instantiate object with constructor
const p1 = new Person('John','Doe','5-Dec-1990');
console.log(p1);
const p2 = new Person();
console.log(p2);
console.log(p1.dob.getFullYear());
console.log(p2.getBirthYear());
console.log(p1.getFullName());
// OOP <ES6-2017> - recommended
class PersonC {
constructor(firstName, lastName, dob) {
// properties
this.fname = firstName;
this.lname = lastName;
// this.dob = dob;
this.dob = (dob === undefined)? new Date(): new Date(dob);
}
getBirthYear = function() {
return this.dob.getFullYear();
}
getFullName = function() {
return `${this.fname} ${this.lname}`;
}
}
const p3 = new PersonC('Jane','Doe','15-Aug-2006');
console.log(p3);
// DOM - Tree structure of your document
console.log(window); // parent object of the browser
//window.alert('alert'); // 'window.' can be omitted
console.log(window.document);
// Selection element in the DOM
// Single element
const form = document.getElementById('my-form');
console.log(form);
console.log(document.querySelector('.container')); // ***
console.log(document.querySelector('#my-form')); // ***
// Multiple element
let items = document.querySelectorAll('.item'); // ***get an Array as output
console.log(items);
items.forEach( item => console.log(item));
// ------ working with the UL in comment -------
// const ul = document.querySelector('.items');
// ul.remove();
// ul.lastElementChild.remove();
// ul.firstElementChild.textContent = 'Hello World';
// ul.children[1].innerText = 'Dome Potikanond';
// ul.lastElementChild.innerHTML = '<h1>The Last Item</h1>';
const btn = document.querySelector('.btn'); // get button element
// btn.style.background = 'tomato'; // change background color of button
// --- What to do when clicking the button? ---
// btn.addEventListener('click', (e) => {
// e.preventDefault(); // prevent the default submit input behavior (no refresh)
// // ---- playing ----
// // console.log('click');
// // console.log(e);
// // console.log(e.target);
// // console.log(e.target.value);
// // document.querySelector('#my-form').style.background = '#ccc';
// // document.querySelector('body').classList.add('bg-dark');
// // document.querySelector('.items').lastElementChild.innerHTML = '<h2> Submit button is clicked! </h2>';
// });
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();
//console.log(nameInput.value);
if (nameInput.value === '' || emailInput === '') {
// alert('Please enter all fields.');
msg.classList.add('error');
msg.innerHTML = 'Please enter all fields';
setTimeout( () => msg.remove(), 3000); // remove msg in 3 seconds
} else {
// console.log('success');
const li = document.createElement('li');
li.appendChild(document.createTextNode(`${nameInput.value} : ${emailInput.value}`));
userList.appendChild(li);
// clear fields
nameInput.value = '';
emailInput.value = '';
}
}
// Next localstorage & Fetch API
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment