Results: 62
Higher order function that receives function as an argument CODE
Built-in built-in higher order functions that expect to receive a function as an argument
document.addEventListener('click', func);
function func() {
    alert('You clicked me!');
}
Using anonymous function:
document.addEventListener('click', function() {
    alert('You clicked me!');
});
Another built-in function
foreach
that receives a function as an argument
let greatColors = ['green', 'orange', 'yellow'];

greatColors.forEach(listColors);

function listColors(color) {
    document.write('The color ' + color + ' is a great color<br>');
}
Benefits of using Higher order function that returns a function CODE
Creates several multiplier functions without using
Higher order function
function doubleMe(number) {
    return 2*number;
}
function tripleMe(number) {
    return 3*number;
}
function quadrupleMe(number) {
    return 4*number;
}
document.write(doubleMe(10));
document.write(tripleMe(10));
document.write(quadrupleMe(10));
Creates the same multiplier functions using
Higher order function
In this case we only need to create one function instead of 3 multiplier functions
function multiplier(multiply) {
    return function(number){
        return number*multiply;
    };
}

let double = multiplier(2);
let triple = multiplier(3);
let quadruple = multiplier(4);

document.write(double(10));
document.write(triple(10));
document.write(quadruple(10));
removeEventListener CODE
First we add
click
event listener for two functions:
func1
,
func2
to document object. After clicking three times we remove the event listener for
func1
function
let counter = 0;
document.addEventListener('click', func1);
document.addEventListener('click', func2);

function func1(){
    console.log('You clicked me!');
  
    if (counter>2) {
        console.log('Max limit is 3');
        document.removeEventListener('click', func1);
    }
}
function func2(){
    counter ++;
    console.log('counter: '+counter);
}
Chaining array functions CODE
Chains several array functions
filter
,
map
together. Uses
onlyMen
and
underTwenty
methods for filtering the result. Uses
onlyNames
function to take only names from the objects.
let people = [
  {name: 'გიორგი', age: 15, gender: 'male'},
  {name: 'ეკატერინე', age: 35, gender: 'female'},
  {name: 'დავითი', age: 75, gender: 'male'},
  {name: 'ნინო', age: 18, gender: 'female'},
  {name: 'თორნიკე', age: 11, gender: 'male'}
]
function onlyMen(human) {
  return human.gender == 'male'
}
function underTwenty(human) {
  return human.age < 20
}
function onlyNames(human) {
  return human.name
}
let onlyBoysNames = people.filter(onlyMen).filter(underTwenty).map(onlyNames)
document.write(onlyBoysNames)
moving from jQuery to native JS
Get element (
input[type=text]
,
select
) value jQuery
let value = $("#element_id").val();
JS
let value = document.getElementById('element_id').value;'
Set value
5
to the specified element (
input[type=text]
,
select
) value jQuery
$("#element_id").val(5);
JS
let value = document.getElementById('element_id').value = 5;'
Check if the specified checkbox is checked jQuery
let is_checked = $("#element_id").is(":checked");
JS
let is_checked = document.getElementById('element_id').checked
Get HTML content of the specified element by element id jQuery
let content = $("#element_id").html();
JS
let content = 
 document.getElementById('element_id').innerHTML
Set HTML content to the specified element by element id jQuery
$("#element_id").html('some html');
JS
document.getElementById('element_id').innerHTML = 'some html'
Get attribute
placeholder
value of the element jQuery
$('#element_id').attr('placeholder');
JS
document.getElementById('element_id').getAttribute('placeholder');
Set attribute
placeholder
value to the specified element jQuery
$('#element_id').attr('placeholder', 'new placeholder');
JS
document.getElementById('element_id').placeholder = 'new placeholder';
Toggle class for an element jQuery
$("#element_id").toggle();
JS
document.getElementById('element_id').classList.toggle("hide");
CSS class
.hide {
	display: none !important;
}
Get selected
radio
value jQuery
let result = jQuery('input:radio[name=vote]:checked').val();
JS
let result = document.querySelector('input[name=vote]:checked').value;
Find
i
element inside another element with id
element_id
jQuery
let icon = $("#element_id").find('i');
JS
document.getElementById('element_id').querySelector('i');
Get
data-value
attribute of
datalist
element using selected text (datalist option's
value
attribute) jQuery
$('#datalist_id [value="selected text"]').data('value');
JS
document.querySelector('#datalist_id option[value="selected text"]').getAttribute('data-value')
Toggle two class for an element jQuery
let el = $('#element')
if(el.hasClass('arrow-down')) {
    el.removeClass('arrow-down');
    el.addClass('arrow-up');
} else {
    el.addClass('arrow-down');
    el.removeClass('arrow-up');
}
JS
let el = document.getElementById('element')
if (el.classList.contains('arrow-up')) {
    el.classList.remove('arrow-up');
    el.classList.add('arrow-down');
} else {
    el.classList.add('arrow-up');
    el.classList.remove('arrow-down');
}
Ajax request jQuery
$.ajax({
    url:'demo_get.asp',
    success:function(sms){
        $('#demo').html(sms);                        
    }
});
JS
var xhttp = new XMLHttpRequest();
xhttp.onreadystatechange = function() {
    if (this.readyState == 4 && this.status == 200) {
        document.getElementById("demo").innerHTML = this.responseText;
    }
};
xhttp.open("GET", "demo_get.asp", true);
xhttp.send();
MouseOver event jQuery
$('#element').on('mouseover', function(){
    console.log('mouse over');
});
JS
document.getElementById('element').addEventListener('mouseover', function(){
    console.log('mouse over');
});
Scroll animation down to the specified element's position in 500 ms jQuery
$('html, body').animate({scrollTop:($('#element').position().top)}, 400);
JS
function scrollDownToElement(el) {

    // Milliseconds per move 
    let pm = 50;

    // Padding from top
    let mft = 150;

    // Total animation milliseconds
    let scroll_ms = 500;

    // Calculates target element top position
    let bd_pos = document.body.getBoundingClientRect();
    let el_pos = document.getElementById(el).getBoundingClientRect();
    let height = el_pos.top-bd_pos.top-mft;

    // Calculates per move px
    let spm = height / (scroll_ms / pm);

    // The animation counter to stop
    let spmc = 1;
    let scroll_timer = setInterval(function() {

        // Moves down by {spm} px
        window.scrollBy(0, spm);
        spmc++;

        // Stops the animation after enough iterations
        if (spmc > (scroll_ms / pm)) {
            clearInterval(scroll_timer);
        }
    }, pm);
}
scrollDownToElement('element');
Arrow function inside "map" function CODE
Regular anonymous function:
let numbers = [10, 100, 1000]

let doubled = numbers.map(function(x){
  return x * 2
})

document.write(doubled)
Alternative arrow function:
let doubled = numbers.map((x) => { return x * 2 })
If it's only a single line we don't need curly brackets and the keyword
return
let doubled = numbers.map((x) => x * 2);
If the arrow function has only one parameter, it does not need parentheses:
let doubled = numbers.map(x => x * 2);
Note: We only need
parentheses
if we had zero or more than one parameters
Default THIS context inside function CODE
this
inside
driveCar()
function refers to the global window object. Global variables
firstName
and
lastName
are added to the
window
object. That is why they are visible using the keyword
firstName = "Jack"
lastName = "Ma"

function driveCar() {
  document.write(this.firstName + ' ' + this.lastName + ' is driving a car<br/>')
}

driveCar()
If we call the same function using
call
function,
this
will refer to the object that will be passed. In this case:
john
object
let john = {
  firstName: 'John',
  lastName: 'Doe'
}

function driveCar() {
  document.write(this.firstName + ' ' + this.lastName + ' is driving a car<br/>')
}

driveCar.call(john)
In JavaScript the statement evaluates to
true
but in PHP it evaluates to
false
if ("0") {
    
}
Let variable scope CODE
Variable described using keyword
let
uses block scope
let myNumber = 1

function callMePlease() {
  let myNumber = 2
  
  if (1 == 1) {
    let myNumber = 3    
    document.write('My number is: ' + myNumber + '</br>')
  }  
  document.write('My number is: ' + myNumber + '</br>')
}

document.write('My number is: ' + myNumber + '</br>')

callMePlease()
element.
childNodes
returns an array of an element's child nodes. element.
firstChild
returns the first child node of an element. element.
lastChild
returns the last child node of an element. element.
hasChildNodes
returns true if an element has any child nodes, otherwise false. element.
nextSibling
returns the next node at the same tree level. element.
previousSibling
returns the previous node at the same tree level. element.
parentNode
returns the parent node of an element.
Results: 62