Basic code for learning Java Script

These are just the notes for simple learning about code for Java Script.

Checking on the console for String, Number Boolean, null, undefined

// String, Number, Boolean, null, undefined

const name = 'John'
const age = 30;
const rating = 4.5;
const isCool = true;
const x = null;
const y = undefined;

console.log(typeof name); // to knowing the type of "name". The type of "name" is string
console.log(typeof age); // to knowing the type of "age". The type of "age" is number.
console.log(typeof rating); // to knowing the type of "rating". The type of "rating" is number.
console.log(typeof isCool); // to knowing the type of "isCool". The type of "IsCool" is boolean.
console.log(typeof x); // to knowing the type of "x". The type of "x" is null. (if spell out of object it is wrong)
console.log(typeof y); // to knowing the type of "y". The type of "y" is undefined. 
console.log(typeof z); // to knowing the type of "z". The type of "z" is undefined.
// String, Number, Boolean, null, undefined

const name = 'john';
const age = '30' ;

// Concatenation
console.log('My name is ' + name + ' and I am ' + age);

// Template String
const hello = `My name is ${name} and I am ${age}`;

console.log(hello);
const s = 'Hello World!';

console.log(s.length); // to count "s" leght of the world

console.log(s.substring(0,5).toUpperCase);// get the string from 0 - 5 , and make it on UpperCase

How To Split

const s = 'Hello World';

console.log(s.split('')); // so we have to look for eacg character

To Look Each word

const s = 'technology, computer, it, code';

console.log(s.split(', ')); // split from the ", "

How to make arrays

// Arrays - variables that hold multiple values

const numbers = new Array(1,2,3,4,5);

console.log(numbers);

multiple data type

const fruits = ['apples', 'oranges', 'pears', 10, true];

console.log(fruits);

How to get data "oranges" from fruits

// Arrays - variables that hold multiple values

const fruits = ['apples', 'oranges', 'pears'];

console.log(fruits[1]);

Add data fruits after "pears"

// Arrays - variables that hold multiple values

const fruits = ['apples', 'oranges', 'pears'];

fruits[3] = 'grapes';
console.log(fruits);
// Arrays - variables that hold multiple values

const fruits = ['apples', 'oranges', 'pears'];
fruits[3] = 'grapes';
fruits.push('mangos'); // use the push to add the end of the data 
fruits.unshift('stawberries'); // use the push to add the frist of the data 
fruits.pop(); // to hiddden last data

console.log(Array.isArray('hello')); // for checking "hello" is array data or not (?)
console.log(fruits.indexOf('oranges')); // to count index of "oranges"
console.log(fruits);
const person = {
    firstName: 'John',
    lastName: 'Doe',
    age: 30,
    hobbies: ['music', 'movies', 'sports'],
    address: {
        street: '50 main st',
        city: 'Boston',
        state: 'MA'
    }
}

console.log(person); // to show of data from "person"
console.log(person.firstName, person.lastName); // to combined the seperate data from "firstName" and "lastName"
console.log(person.hobbies[1]); // to get the "movies" from hobbies
console.log(person.address.city); // to get the "bostin" from city of addresss

// --- to make variable
const { firstName, lastName, address: { city}} = person;
console.log(city); 
// ***

// --- to make variable
const { firstName, lastName } = person;
console.log(firstName);
// ***

Array Of Obejct

const todos = [
{
    id: 1,
    text: 'Text out trash',
    isCompleted: true
},
{
    id: 1,
    text: 'Meeting with boss',
    isCompleted: true
},
{
    id: 1,
    text: 'Dentist appt',
    isCompleted: true
},
]

console.log(todos); // to show todos 
console.log(todos[1]); // to get "meeting with boss"
console.log(todos[1].text); // to change the data to text

Convert to JSON

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

For Loop

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

// For Loop with the description text
for(let i = 0; i <= 10; i++) {
    console.log(`For Loop Number: ${i}`);
}

For While Loop

// While
let i = 0;
while(i < 10){
    console.log(`while Loop Number: ${i}`);
    i++;
}

The best way to loop

for(let i = 0; i < todos.length; i++) {
    console.log(todos[i].text);
}
// for Each
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);
// filter with also map to get the text

Java Conditions and If Statements

const x = 4;

if(x === 10) {
    console.log('x is 10');  
} else if(x > 10) {
    console.log('x is greater than 10');
} else {
    console.log('x is less than 10');
}
const x = 6;
const y = 11;

if(x > 5 && y > 10) {
    console.log('x is more than 5 or y is more than 10');
}
// alternatif double if
if (x > 5) {
    if (y > 10) {
console.log('x is more than 5 or y is more than 10')
} 
}
const x = 11;

const color = x > 10 ? 'red' : 'blue';

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;
}

Java Function

function addNums(num1, num2) {
    console.log(num1 + num2);
} 

console.log(addNums(5,5));
const addNums = (num1 = 1, num2 = 1) => {
    return num1 + num2;
}

console.log(addNums(5,5));
const addNums = num1 => num1 + 5;

console.log(addNums(5));

// todos.forEach((todo) => console.log(todo));

Construct Function

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

// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person2.firstName); // to call name
console.log(person2.dob.getFullYear()); // to call date by year
// Constructor function
function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob);
    this.getBirthYear = function() {
        return this.dob.getFullYear();
    }
    this.getFullName = function() {
        return `${this.firstName} ${this.lastName}`;
    }
}

// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person1.getBirthYear());
console.log(person1.getFullName());
// Constructor function
function Person(firstName, lastName, dob){
    this.firstName = firstName;
    this.lastName = lastName;
    this.dob = new Date(dob);
}

Person.prototype.getBirthYear = function() {
    return this.dob.getFullYear();
}

Person.prototype.getFullName = function() {
    return `${this.firstName} ${this.lastName}`;  
}

// Instantiate object
const person1 = new Person('John', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

console.log(person2.getFullName);
console.log(person1);
// Class
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', 'Doe', '4-3-1980');
const person2 = new Person('Mary', 'Smith', '3-6-1970');

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

Code to make login page HTML

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge" />
    <title>JS For Beginners</title>
    <link rel="stylesheet" href="style.css">
</head>
<body>
    <header>
        <h1>JS For Beginners</h1>
    </header>
    <section class="container">
        <form id="my-form">
            <h1>Add User</h1>
            <div class="msg"></div>
            <div>
                <label for="name"> Name:</label>
                <input type="text" id="name">
            </div>
            <div>
                <label for="email">Email:</label>
                <input type="text" id="email">
            </div>
            <input class="btn" type="submit" value="Submit">
        </form>

        <ul id="users"></ul>
        <!--- <ul class="items">
<li class="item">Item 1</li>
<li class="item">Item 2</li>
<li class="item">Item 3</li>
        </ul>   -->

    </section>

    <script src=main.js"> </script>
</body>
</html>

Selected

to check

console.log(document.getElementById('my-form'));
// Single element
// 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));
const ul = document.querySelector('.items');

// ul.remove();
// ul.lastElementChild.remove();
ul.firstElementChild.textContent = 'Hello'; // to edit content
ul.children[1].innerText = 'Brad';
ul.lastElementChild.innerHTML = '<h1>hello</h1>';

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

// event, you are clicked

btn.addEventListener('click', (e) => {
    e.preventDefault();
    console.log(e.target.id);  // change this to your needed 
});
const btn = document.querySelector('.items');

// event you are click

btn.addEventListener('click', (e) => {
    e.preventDefault();
    document.querySelector('#my-form').style.background = 
    '#ccc';

});

for the style.css



body {
    font-family: Arial, Helvetica, sans-serif;
    line-height: 1.6;
}

ul {
    list-style: none;
}

ul li {
    padding: 5px;
    background: #f4f4f4;
    margin: 5px 0;
}

header {
    background: #f4f4f4;
    padding: 1rem;
    text-align: center;
}

.container {
    margin: auto;
    width: 500px;
    overflow: auto;
    padding: 3rem 2rem;
}

#my-form {
    padding: 2 rem;
    background: #f4f4f4;
}

#my-form label {
    display: block;
}

#my-form input[type='text'] {
    width: 100%;
    padding: 8px;
    margin-bottom: 10px;
    border-radius: 5px;
    border: 1px solid #ccc
}

.btn {
    display: block;
    width: 100%;
    padding: 10px 15px;
    border: 0;
    background: #333;
    color: #fff;
    border-radius: 5px;
    margin: 5px 0;
}
.btn:hover {
    background: #444;
}
.bg-dark {
    background: #333;
    color: #fff;

.error {
    background: orangered;
    color: #fff;
    padding: 5px;
    margin: 5px;
}
}

Changed background to the dark color

const btn = document.querySelector('.btn');

// event you are click

btn.addEventListener('click', (e) => {
    e.preventDefault();
    document.querySelector('#my-form').style.background = 
    '#ccc';
    document.querySelector('body').classList.add('bg-dark');

});
const btn = document.querySelector('.btn');

// event you are click

btn.addEventListener('click', (e) => {
                // moverover for when mount on over 
                // mouseout for when to mouse out from button
    e.preventDefault();
    document.querySelector('#my-form').style.background = 
    '#ccc';
    document.querySelector('body').classList.add('bg-dark');
    document.querySelector('.items')
    .lastElementChild.innerHTML = '<h1>hello</h1>'
});
// function of litte input and output aplication, 

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);
}
// function of litte input and output aplication, 

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 = '';
    }

}

Did you find this article valuable?

Support Meg Pamungkas by becoming a sponsor. Any amount is appreciated!