// 1. let, const
const age = 30; // can not leave variable unsigned
age = 31; // ERROR
console.log(age);
let age = 30; // less robust
age = 31;
console.log(age);
// ===============================================
// 2. String, Numbers, Boolean, null, undefined
const name = 'John';
const age = 29;
const rating = 4.5;
const isCool = true;
const x = null; // object
const y = undefined; // undefined
let z; // undefined
console.log(typeof z) // try defferent variables
// ================================================
// 3. String
const name = 'Jhon';
const age = 30;
// Concatenation
console.log("My name is " + name + " and I'm " + age + ".");
// Template string
const hello = `My name is ${name} and I'm ${age}.`;
console.log(hello);
console.log(hello.length); // property doesn't have '()', method does
console.log(hello.toUpperCase());
console.log(hello.toLowerCase());
console.log(hello.substring(0, 2).toUpperCase());
console.log(hello[1].toUpperCase());
console.log(hello.split(''));
console.log(hello.split(' '));
// ==================================================
// 4. Arrays - varibles hold multiple values
const numbers = new Array(1, 2, 3, 4); // constructor
const fruits = ['apple', 'banana', 'orange'];
const whatever = [fruits, 'hello', numbers, 10, true, null, undefined];
fruits[3] = 'grape'; // the members can be manipulated eventhough the array is a constant
fruits.push('mango');
fruits.unshift('strawberry');
fruits.pop();
console.log(fruits);
console.log(fruits[1]);
console.log(Array.isArray(fruits));
console.log(Array.isArray('hello'));
console.log(fruits.indexOf('orange'));
// ====================================================
// 5. Object literals
const person = {
first_name: 'John',
last_name: 'Doe',
age: 30,
hobbies: ['music', 'movies', 'sports'],
address: {
street: '50 main st',
city: 'Boston',
state: 'MA',
},
};
console.log(person);
console.log(person.first_name, person.last_name);
console.log(person.hobbies[0]);
const { first_name, last_name, address:{city} } = person; // destruct
console.log(city)
person.email = 'johndoe@gmail.com'
console.log(person)
// ==========================================
// 6. arrays of Objects and JSON, and Loop
const todos = [
{
id: 0,
text: 'Take out trash',
isCompleted: true,
},
{
id: 1,
text: 'Read books',
isCompleted: true,
},
{
id: 2,
text: 'Go shopping',
isCompleted: false,
},
];
console.log(todos[1].text)
// convert to JSON
// manually: https://www.freeformatter.com/json-formatter.html
// OR:
const todosJSON = JSON.stringify(todos);
console.log(todosJSON);
// Loop
// Iterator - For
for (let i = 0; i <= 10; i++) {
console.log(`For Lpop Number: ${i}`)
};
// Iterator - While
i = 0;
while (i <= 10) {
console.log(`While Lpop Number: ${i}`)
i++;
};
// Loop through an Array
for (let i = 0; i < todos.length; i++) {
console.log(todos[i].text)
};
// better one:
for (let todo of todos) {
console.log(todo.text)
};
// much better:
// forEach, map, filter
todos.forEach(function(todo) {
console.log(todo.text)
});
const todoText_list = todos.map(function(todo) {
return todo.text
});
console.log(todoText_list);
const todoCompleted_list = todos.filter(function(todo) {
return todo.isCompleted === true
});
console.log(todoCompleted_list);
const todoCompletedText_list = todos.filter(function(todo) {
return todo.isCompleted === true
}).map(function(todo) {
return todo.text
});
console.log(todoCompletedText_list);
// =============================================
// 8. Conditional
// if statement
const x = '10';
if (x == 10) {
console.log('x is 10')
};
if (x === 10) {
console.log('x is a number 10')
} else {
console.log('x is NOT a number 10')
};
const y = true;
if (y == 10) {
console.log('y is 10')
} else if (y > 10) {
console.log('y is greater than 10')
} else if (y < 10) {
console.log('y is less than 10')
} else {
console.log('y is NOT a number or can NOT convert to a number')
};
if (x >= 10 || y >= 10) {
console.log('x is no less than 10 or y is no less than 10')
} else {
console.log('both x and y are less than 10')
};
if (x <= 10 && y <= 10) {
console.log('both x and y are no more than 10')
} else {
console.log('x is no mor than 10 or y is no more than 10')
};
// switch statement
const color1 = x == 10 ? 'red' : 'blue';
console.log(color1);
const color2 = 'green'
let color
switch (color = color2) {
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;
};
// ===============================================
// 9. function
function addNums(num1=1, num2=2) {
added = num1 + num2
console.log(added)
return added
};
addNums()
addNums(4, 5)
addNums('4', '5')
const addNums2 = (num1=1, num2=2) => {
added = num1 + num2
return added
};
console.log(addNums2(4, 5))
const addNums3 = (num1=1, num2=2) => num1 + num2;
console.log(addNums3(4, 5))
const addNums4 = num1 => num1 + 5;
console.log(addNums4(4))
// ==================================
// // 10. OOP
// *. date time ********************************************************
// Constructor
const nameOfMonths = [
"January", "February", "March", "April", "May", "June", "July",
"August", "September", "October", "November", "December"
]
const nameOfDays = [
"Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday"
]
function getDateTime(date=Date()) {
this.date = new Date(date);
this.day = nameOfDays[this.date.getDay()].substr(0,3);
this.hr = this.date.getHours();
this.mnt = this.date.getMinutes();
this.scd = this.date.getSeconds();
this.hr_mnt_scd = `${this.hr}:${this.mnt}:${this.scd}`
this.dd = this.date.getDate();
this.mm = nameOfMonths[this.date.getMonth()].substr(0, 3);
this.yy = this.date.getFullYear()
this.mm_dd_yy = `${this.mm}-${this.dd}-${this.yy}`
}
// There are 4 ways to create a new date object:
// new Date()
// new Date(year, month, day, hours, minutes, seconds, milliseconds)
// new Date(milliseconds)
// new Date(date string)
// Instantiate object
const now = new getDateTime()
const date = new getDateTime('12-31-2001')
console.log(now.day, now.hr_mnt_scd, now.mm_dd_yy)
// ********************************************************
/* // Constructor
function Person(firstName, lastName, dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = new getDateTime(dateOfBirth);
}
// Prototype
Person.prototype.getFullName = function () {
return `${this.firstName} ${this.lastName}`;
}
Person.prototype.getBirthMDY = function () {
return this.dateOfBirth.mm_dd_yy;
}
*/ // same as class below
// Class
class Person {
constructor(firstName, lastName, dateOfBirth) {
this.firstName = firstName;
this.lastName = lastName;
this.dateOfBirth = new getDateTime(dateOfBirth);
}
getFullName() {
return `${this.firstName} ${this.lastName}`;
}
getBirthMDY() {
return this.dateOfBirth.mm_dd_yy;
}
}
// Instantiate object
const person1 = new Person('John', 'Doe', '4-9-1990');
const person2 = new Person('Mary', 'Smith', '1-31-1990');
console.log(person1);
console.log(person2.dateOfBirth);
console.log(person2.getFullName());
console.log(person2.getBirthMDY());
// =======================================================
// Selectors
// Single element
console.log(window)
console.log(document.getElementById("my_form"));
console.log(document.querySelector("h1"));
// Multiple element
console.log(document.querySelectorAll(".item"));
console.log(document.getElementsByClassName("item"));
console.log(document.getElementsByTagName("li"))
const items = document.querySelectorAll('.item');
items.forEach((item) => console.log(item));
ul = document.querySelector(".items");
console.log(ul);
console.log(ul.lastElementChild);
console.log(ul.children[1]);
// ul.remove();
// ul.lastElementChild.remove();
ul.firstElementChild.textContent = "hello";
ul.children[1].innerText = "bread";
ul.firstElementChild.innerHTML = "<h4>Hello</h4>";
const btn = document.querySelector(".btn");
btn.style.background = 'orange';
btn.addEventListener('click', (e)=>{
e.preventDefault();
console.log('click');
document.querySelector('#my_form').style.background = '#ccc';
document.querySelector('body').classList.add('bg-dark');
});
const my_form = document.querySelector("#my_form")
const name_input = document.querySelector("#name")
const email_input = document.querySelector('#email')
const msg = document.querySelector('.msg')
const user_li = document.querySelector('#users')
my_form.addEventListener('submit', onsubmit);
function onsubmit(e) {
e.preventDefault();
if (name_input.value==='' || email_input.value==='') {
msg.innerHTML = "please enter name and email"
msg.classList.add("error")
} else {
msg.innerHTML = ""
const li = document.createElement('li')
li.appendChild(document.createTextNode(`${name_input.value}: ${email_input.value}`))
user_li.appendChild(li);
name_input.value = "";
email_input.value = "";
}
}