Last Updated:

ECMAScript 6 - JavaScript

ECMAScript 6 (or ES6) is a new version of JavaScript 2015, which adds new functionality, which today is supported by all modern browsers.

Variables and comments

JavaScript is not a strongly typed language. Variables are denoted as follows:

 let name='Gennady'//String
console.log(name) //Gennady - displayed in the console

var age=40 //Number(without quotes) VAR (global) - deprecated, do not use!
console.log(age)//40 - displayed in the console

const prof="Programmer"//This is a constant
console.log(prof)//Programmer - displayed in the console

// is a single line comment

/*
here
multiline
comments
*/

Data Types

 

The ECMAScript standard defines 9 types:

  • 6 types of data being primitives:
    • Undefined : typeof instance === "undefined"
    • Boolean : typeof instance === "boolean"
    • Number : typeof instance === "number"
    • String : typeof instance === "string"
    • BigInt : typeof instance === "bigint"
    • Symbol (in ECMAScript 6) : typeof instance === "symbol"
  • Null : typeof instance === "object". A special primitive used not only for data but also as a pointer to the final point in the Prototype Chain;
  • Object : typeof instance === "object". A simple structure used not only to store data, but also to create other structures, where any structure is created using the keyword new: new Object, new Array, new Map (en-US), new Set, new WeakMap, new WeakSet, new Date and many other structures;
  • Function : typeof instance === "function". A special case that simplifies type definition for Functions, even though all functions are structurally inherited from Object.
 let name='Gennady'//String
console.log(typeof name) //string - displayed in the console
console.log(typeof(name))//string - displayed in the console

Conditions, comparison operators (if-else, ternary, switch)

 let a=10, b=10//Variables
if (a>b) {
console.log(`${a} is greater than ${b}`)//10 is greater than 10
} else if(a<b) {
console.log(`${a} is less than ${b}`)//10 is less than 10
} else {
console.log(`${a} is equal to ${b}`)//10 is equal to 10
}


let age=10//Age
let rez = (age > 18) ? 'Adult' : 'Child' // Ternary (or conditional) operator
console log(rez);


let v=10//Age
switch(v){
case 10:
result='v=10';
break;

case 20:
result='v=20';
break;

default:
result = 'v != 10 and v != 20';
break;
    }
    console log(result)

Creating Functions

    //Function declaration
function f1(name) {
return 'Hello, '+name
}
console.log(f1('Vanya'))


    //Function expression
const f2=function (name) {
return 'Hello, '+name
}
console.log(f2('Anna'))


    // Arrow functions
const f3=(name) => {
return 'Hello, '+name
}
console.log(f3('Danya'))


    // Arrow functions
const f4=(name) => 'Hi, '+name//Abbreviated
console.log(f4('Sanya'))


    // Self-calling function
;(function f5 (name) {
console.log('Hi, '+name)
})('Mania')  

Arrays

An array in JavaScript is a global object that is used to create arrays; which are high-level list-like objects.

    const arr=[1,2,3]
//const arr = new Array(4,5,6)//The old way
console.log(arr) //(3) [1, 2, 3]
console.log(arr[1])//2

console.log(arr.length)//Array length

//Adding an element to the end of the array
arr.push('Orange');
console.log(arr)//[1, 'Tea', 3, 4, 5, 'Orange']

//Remove the last element of the array
arr.pop()// remove the Orange (from the end)
console.log(arr)//[1, 'Tea', 3, 4, 5]

//Remove the first element of the array
arr.shift(); // remove the element (from the beginning)
console.log(arr)//['Tea', 3, 4, 5]

//Adding an element to the beginning of the array
arr. unshift('Strawberry') // adds to the beginning
console.log(arr)//['Strawberry', 'Tea', 3, 4, 5]

//Search for the element number in the array
let pos = arr.indexOf('Tea')
console.log(pos)//1 - index

//Remove multiple elements starting at a specific index
arr.splice(1, 2); // this way you can remove the element
console.log(arr)//['Strawberry', 4, 5]

//Create a copy of the array
const newArr = arr.slice(); // so you can create a copy of the array
console.log(newArr)//['Strawberry', 4, 5

//Iterate over array
arr.forEach(function(item, i, array) {
console log(item, i);
});

An associative array in JS is an object (see below...)

Cycles

 for (let i=1; i<=5; i++) {
console.log(i)//outputs
}


let j=1
while (j<=5) {
console.log(j++)//outputs
}

Traversing an array with a for loop

 const fruits = ['Apple', 'Banana', 'Strawberry', 'Mango'];

//With for
for (let i=0; i<fruits.length; i++) {
console.log(fruits[i])//Prints items
}

// for ( of ) loop
for (let value of fruits) {
console.log(value);//Displays the elements
}

//Iterate over array
fruits.forEach(function(item, i, array) {
console log(item, i);
});

//Iterating over an array - Short notation (arrow)
fruits.forEach((item, i, array) => console.log(item, i));

 

Objects. Object properties

An object in JavaScript is a set of properties, and each property consists of a name and a value associated with that name.

 const person = {
name:'Gennady',
age:40,
sayHi:function(p){
return `Hello ${p} ${this.name}`
},
}

console.log(person) //{name: 'Gennady', age: 40, sayHi: ƒ}
console.log(person.name) //via . - Gennady
console.log(person['age'])//through [''] - 40
console.log(person.sayHi('comrade'))//Hello, comrade Gennady

person.prof = 'Programmer'//Add property or method()
console.log(person) //{name: 'Gennady', age: 40, prof: 'Programmer', sayHi: ƒ}

delete person.prof //Delete a property
console.log(person) //{name: 'Gennady', age: 40, sayHi: ƒ}

Обход свойств объекта через цикл for ( in )

 for(key in person) {
console.log(`${key} - ${person[key]}`)//Prints items
}

Classes. Object constructors

Classes are used to describe similar objects.

 class MyClass {
constructor(name, age) {
this.name = name
this.age = age
}

sayHi(p){
return `${p}, ${this.name}`;
}
}

user1=new MyClass('Gene','40')
console.log(user1.name)//Gena
user1.name='Gennady'//Change the value
console.log(user1.sayHi('Hello'))//Hello Gennady

user2=new MyClass('John','40')
console.log(user2.sayHi('Hello'))//Hello Ivan


//New class from parent MyClass - Inheritance
class NewClass extends MyClass {
seyHi(p){
return `${p} ${this.name} - ${this.age} rub !`;//Override method
}
}

user3=new NewClass('Sofa','100')
console.log(user3.seyHi('Sell'))//Sell Sofa !

Working with the DOM - Selecting DOM Elements

 const h1=document.querySelector("#h1")//Selection like CSS - by id, class or tag
h1.innerHTML='<i>New</i> header';//Insert text with tags inside the selected element; .innerText - text only

Working with the DOM - Selecting a Collection of Elements

const p=document.querySelectorAll('p')
//console.log(p)

for (let v of p)
{
v.classList.add('red')//All <p> add class="red"
}
  • document.getElementById(id);
  • el.getElementsByTagName(tag) searches for items with this tag and returns a collection of them. By passing a "*" instead of a tag, you can get all the descendants.
  • el.getElementsByClassName(className) returns elements that have this CSS class.
  • document.getElementsByName(name) returns elements with the specified name attribute. Very rarely used.

Working with CSS Classes

The .classList methods are:

  • .add( className1[,className2,...] ) - adds one or more of the specified classes to the element. If an element already has this class, it will not be added to it.
  • .remove( className1[,className2,... ] ) - Removes one or more of the specified classes from an element. If an element does not have a class that you want to delete, no action will be taken.
  • .contains( className ) – checks whether the element has a class; returns true or false as the response.
  • .toggle( className [,flag] ) - toggles the specified class name for the element, i.e. if the element has this class, then removes it; otherwise adds. The second parameter (flag) is optional. By default, it is set to undefined. If you set it to true or false, it will work as an add or remove method, which means either adding a class to an element or removing it from it.
 /*
An example in which we perform various operations on the element class using the className DOM property:
*/

el.className = 'alert'; // add class to element
el.className = 'alert-warning'; // change the class of the element
let E1 = el.className; // get the class value and store it in className
el.className = ""; // remove the class from the element

Working with Attributes

 /*
An example in which we perform actions like the above code, but using methods to manage attributes:
*/

el.setAttribute('class', 'alert');// add a class to the element
el.setAttribute('class', 'alert-warning');// change the class of the element
let E2 = el.getAttribute('class'); // "alert-warning"// get the class value and store it in className
el.removeAttribute('class');// remove class from element

Replace picture

 const img=document.querySelector('#logo')//Select like CSS - by id
console.log(img.getAttribute('src')) //flexbox/person.jpg

img.setAttribute('src', 'flexbox/22_Viber.png')//Change attribute value (picture)
img.setAttribute('width', '100'); //Change the size - width="100"

img.src='flexbox/person.jpg'//And you can change the src attribute like this

Wiretaps

An event is a signal from the browser that something has happened. All DOM nodes give such signals (although events occur not only in the DOM).

Here's a list of the most commonly used DOM events, so far just for a read:

Mouse Events:

  • click – occurs when the element is clicked with the left mouse button (on devices with touch screens, it occurs when touched).
  • contextmenu – occurs when an element is right-clicked.
  • mouseover / mouseout – when the mouse is hovered over / leaves the element.
  • mousedown / mouseup – when you press / press the mouse button on the element.
  • mousemove – when the mouse moves.

Events on controls:

  • submit–The user submitted a form <form>.
  • focus–The user focuses on the element, such as clicking on the <input>.

Keyboard events:

  • keydown and keyup – when the user presses/releases a key.

Document Events:

  • DOMContentLoaded – When the HTML is loaded and processed, the DOM of the document is fully built and available.

CSS events:

  • transitionend – when the CSS animation is complete.

There are three ways to assign event handlers:

  1. HTML attribute: onclick="...".
  2. DOM property: elem.onclick = function.
  3. Special methods: elem.addEventListener(event, handler[, phase]) to add, removeEventListener to remove.

A handler can be assigned directly in the markup, in an attribute called on< event>.

	<input value="Нажми меня" onclick="alert('Клик!')" type="button">
 const img=document.querySelector('#logo')//Select like CSS - by id
img.onclick = function() {
alert('Thank you');
}

img.addEventListener('click', () => alert('You clicked on the image'));
 function handler() {
alert('Thank you!');
}

img.addEventListener("click", handler);//added an event
img.removeEventListener("click", handler);//deleted the event


document.addEventListener("DOMContentLoaded", function() {
alert("DOM built");//DOM loaded and built
});

Event object

 const img=document.querySelector('#logo')//Select like CSS - by id

//output event type, element and click coordinates
img.onclick = function(event) {
alert(event.type + " to " + this.getAttribute('src')) //click on flexbox/person.jpg
alert("Coordinates: " + event.clientX + ":" + event.clientY)//Coordinates: 35:175

//img.remove();//Remove the image (the entire img tag)
this.remove();//Remove the image (the whole img tag)
}

If addEventListener receives an object as a handler, it calls object.handleEvent(event) when an event occurs. We can also use the class to do this:

 const img=document.querySelector('#logo')//Select like CSS - by id
const h1=document.querySelector('#h1') //Select like CSS - by id

class menu {
handleEvent(event) {

switch(event type) {
case 'mousedown':
h1.innerHTML = "Mouse button pressed";
break;

case 'mouseup':
h1.innerHTML += "...and out.";
break;
}
}
}

letmenu = newMenu();
img.addEventListener('mousedown', menu);
img.addEventListener('mouseup', menu);

or

 const img=document.querySelector('#logo')//Select like CSS - by id
const h1=document.querySelector('#h1') //Select like CSS - by id

class menu {
handleEvent(event) {
// mousedown -> onMousedown
let method = 'on' + event.type[0].toUpperCase() + event.type.slice(1);
this[method](event);
}

onMousedown() {
h1.innerHTML = "Mouse button down";
}

onMouseup() {
h1.innerHTML += "...and out.";
}
}

letmenu = newMenu();
img.addEventListener('mousedown', menu);
img.addEventListener('mouseup', menu);

/*
class menu {
handleEvent(event) {
this[event.type](event);
}

mousedown(e) {
h1.innerHTML = "Mouse button down";
}

mouseup(e) {
h1.innerHTML += "...and out.";
}
}
*/

Output text from <input> in <p>

 const iTxet=document.querySelector('#iTxet')//Select like CSS - by id
const pTxet=document.querySelector('#pTxet')//Select like CSS - by id

iTxet.addEventListener('input', function(){
pTxet.innerText = iTxet.value;
});  

Task list on JS

To insert an HTML block, use the method: elem.insertAdjacentHTML(where, html).

The first parameter is a special word that indicates where to insert in relation to elem. The value must be one of the following:

  • "beforebegin" – insert html just before elem,
  • "afterbegin" – insert html into the beginning of elem,
  • "beforeend" – insert html at the end of elem,
  • "afterend" – insert html directly after elem.

The second parameter is an HTML string, which will be inserted "as HTML".

<ul id="iUl">
<li>Breakfast</li>
<li>Lunch</li>
<li>Dinner</li>
</ul>

<form id="iSu">
<input type="text" name="" id="iTx">
<input type="submit" name="">
</form>  
 const iSu=document.querySelector('#iSu')//Select like CSS - by id
const iTx=document.querySelector('#iTx')//Select like CSS - by id
const iUl=document.querySelector('#iUl')//Select like CSS - by id

iSu.addEventListener('submit', function(e){
e.preventDefault() //Cancel default browser action (reload)
let text = iTx.value//Get value from input

//1st option
//let liText=`<li>${text}<\li>`//Form the list item
//iUl.insertAdjacentHTML('beforeend', liText);//Insert html at the end

//2nd option
let liText=document.createElement('li')//Create the li tag
liText.innerText=text//Add input content to it
iUl.append(liText)//Insert html at the end
//+BUTTON
let button=document.createElement('button')//Create a button tag - a button
button.setAttribute('rote', 'button');//On button attribute rote='button'
button.innerText='Remove' //On button text Delete
button.style['margin-left']='15px' //On button style
liText.append(button) //Insert a button at the end of li
//+Event on the button
/*
button.addEventListener('click', function(e){
this.closest('li').remove()//Looking for the button's parent - the li tag - removing it
})
// OR
*/
button.addEventListener('click', (e)=>e.target.closest('li').remove())//Search for the button's parent - li tag - remove it

iTx.value=''//Clear the input field
iTx.focus() //Focus on input
});

Interval setInterval - clearInterval

 let h1=document.querySelector("#h1"), i=0;
/*
setInterval(function() {
h1.innerHTML=++i
}, 1000)
*/

let t=setInterval(() => {
h1.innerHTML=++i//Every sec. +1
}, 1000)


h1.onclick = function() {
clearInterval(t)//Stop on click
}

setTimeout timer

 const h1=document.querySelector("#h1")

setTimeout(function(){
h1.innerHTML='It worked!!!'
}, 3000)

Stopwatch

 let h1=document.querySelector("#h1"), i=0;

let t=setInterval(() => {
h1.innerHTML=++i//Every sec. +1
}, 1000)

setTimeout(() => {
clearInterval(t)//Stop after 5 seconds
}, 5000)