Borrowing a method from another object
The methods call, apply and bind are used to define the meaning of the reserved word this, however this also allows us that by changing the meaning of “this” an object can “borrow” a method from another object, as in the following example:
|
1 2 3 4 5 6 7 8 9 10 |
objekat1 = { name:'Pera', greet:function(){ alert('Hello, '+this.name) } }; objekat2 = { name:'Mika' }; objekat1.greet.call(objekat2); // Returns: Hello Mika |
It is often the case that one of the methods of Array that are built into its prototype object is borrowed.
|
1 |
Array.prototype.slice.call (someObject); |
In this way, we borrowed Array’s slice method to some object.
Converting array like objects to string

In JavaScript, there are “array-like” objects, which look like arrays but are not arrays (eg NodeList). Such objects do not have all the methods that a standard array has, e.g. slice, concat, sort, reduce, map, filter… There may also be a need to transfer the arguments object that stores the arguments of the function to an array or even to transfer a string to an array. Converting “array like” objects into a standard string can be done in several ways:
“Array-like” object into an array with the slice() method. But the slice() method is not available, so we have to use the call() method to “borrow” the slice() method from arrays. So the final expression would look like this:
|
1 2 3 4 |
Array.prototype.slice.call (arrayLike) // Identical functionality is often seen, but written shorter: [].slice.call(arrayLike) |
If there is a lot of manipulation with DOM and arrayLike objects, it is good to create a function, and call it whenever necessary:
|
1 2 3 4 5 6 7 8 9 10 |
function napraviNiz (arrayLike) { return Array.prototype.slice.call(arrayLike); } // Example: var checkBoxObject = document.querySelectorAll('input'); var checked = napraviNiz(checkBoxObject); checked.forEach(function(arrayItem) { console.log(arrayItem.value); }); |
Using the from() function which easily converts all array-like elements to a standard array
|
1 |
Array.from(arrayLike, [nekaMapFunkcija, [thisArg]]) |
- arrayLike – the name of the element to be transferred to the array
- someMapFunction – An optional Map function that can be called for each element of the array
- thisArg – the value to which the this keyword will point within the map function
|
1 |
var konvertovanNiz = [...arrayLike]; |
Using the jQuery.makeArray() function we simply pass the array-like
objects into an array:
|
1 |
$.makeArray(arrayLike); |
Checking the variable with “!!” operator
If there is a need to check if a variable exists and has a valid value, the easiest way is to use the expression !!variable. This expression automatically converts to a boolean value, and if the value of the variable is undefined, “”, 0, null, or NaN it returns FALSE, otherwise it returns TRUE. The same effect is obtained using the Boolean(el).
function
Example
|
1 2 3 4 5 6 7 8 9 10 11 |
function Racun(kes) { this.kes = kes; this.imaPare = !!kes; // Isti efekat this.imaPare = Boolean(kes); } var nekiRacun = new Racun(100.50); console.log(nekiRacun.kes); // 100.50 console.log(nekiRacun.imaPare); // Returns: TRUE var emptyRacun = new Racun(0); console.log(emptyRacun.kes); // 0 console.log(emptyRacun.imaPare); // Returns: FALSE |
Hide images with error
Targeting images with errors is possible thanks to the fact that the browser fires an error event when it cannot find an image.
|
1 2 3 |
$("img").error(function(){ $(this).hide(); }); |
Sticky header
See the Pen Sticky Title by Web programming (@chos) on CodePen.
NOTE:
The classList object is not supported by IE for versions less than IE10
Scroll to the top
HTML
|
1 |
<button id="top">na vrh</button> |
JavaScript
|
1 2 3 4 |
$("#top").click(function() { $("html, body").animate({ scrollTop: 0 }, "slow"); return false; }); |
Autogrowing textarea
See the Pen Auto-increasing text area by Web programming (@chos) on CodePen.
Browser detection
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 |
function BrowserDetection() { // Provera da li je IE if (navigator.userAgent.search("MSIE") >= 0) { // goes here kondicionalni kod za IE } // Provera da li je Chrome else if (navigator.userAgent.search("Chrome") >= 0) { // goes here kondicionalni kod za Chrome } // Provera da li je Firefox else if (navigator.userAgent.search("Firefox") >= 0) { // goes here kondicionalni kod za Firefox Code here } // Provera da li je Safari else if (navigator.userAgent.search("Safari") >= 0 && navigator.userAgent.search("Chrome") < 0) { // goes here kondicionalni kod za Safari } // Provera da li je Opera else if (navigator.userAgent.search("Opera") >= 0) { // goes here kondicionalni kod za Opera } } |
Effects: fadeOut & fadeIn
|
1 2 3 4 5 6 7 8 9 10 11 12 |
function fadeOut(el, duration) { var s = el.style, step = 25/(duration || 300); s.opacity = s.opacity || 1; (function fade() { (s.opacity -= step) < 0 ? s.display = "none" : setTimeout(fade, 25); })(); } function fadeIn(el, duration, displayType) { var s = el.style, step = 25/(duration || 300); s.opacity = s.opacity || 0; s.display = displayType || "block"; (function fade() { (s.opacity = parseFloat(s.opacity)+step) > 1 ? s.opacity = 1 : setTimeout(fade, 25); })(); } |
Example
See the Pen FadeOut/FadeIn effect by Web programming (@chos) on CodePen.
|
1 2 |
$("selector").fadeOut(duration) $("selector").fadeIn(duration) |
Example
See the Pen Fadeout/Fadein jQuery by Web programming (@chos) on CodePen.
Replace part of the text in the string
Replacing part of the text in a string is done with the string method replace(). This method returns a new string with the replaced parts:
|
1 |
nekiString.replace(regex|deoZaZamenu, newWord|function) |
regex is either a literal or a RegExp constructor that creates a regular expression pattern. The most common flags used are:
- g – globally finds all matches (if there is none, the search stops when it finds the first match!)
- i – ignores case
Example
|
1 2 3 |
var str = 'Apples are round, and apples are juicy.'; var newstr = str.replace(/apples/gi, 'oranges'); console.log(newstr); // Returns: "oranges are round, and oranges are juicy." |
String search
The String.prototype.indexOf() method returns the index of the first found string within the string, the optional second attribute defines the index from which to start the search.
|
1 |
nekiString.indexOf(searchValue[, fromIndex]) |
If the requested string is not found, the method returns the value -1. Please note that this function is case sensitive.. See more about this method in the documentation at MDN developer.mozilla
|
1 2 3 4 |
var nekiString ="Dobar programer"; console.log(nekiString.indexOf('programer')); // Returns: 6 console.log(nekiString.indexOf('Programer')); // Returns: -1 console.log(nekiString.indexOf('r')); // Returns: 4 |
If two attributes are used in the indexOf() method, then the second attribute defines from which index to start the search.
Example
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
function pretraziString(element, string) { var nadjeniClanovi = []; var brojac = 0; var indexNadjenog = string.indexOf(element); while (indexNadjenog != -1) { brojac++; nadjeniClanovi.push(indexNadjenog); indexNadjenog = string.indexOf(element, indexNadjenog + 1); // Note: the second attribute defines from which index to start the search } console.log("Element se pojavljije " + brojac + " puta, na mestima sa index-om ", nadjeniClanovi); } var str = 'This is some string'; pretraziString ("e", str); // Returns: "Element se pojavljije 2 puta, na mestima sa index-om " [5, 8] |
Example: filtering a list
See the Pen Filter list by Web programming (@chos) on CodePen.
Counting words in the text
See the Pen vJEdWd by Web programming (@chos) on CodePen.
Rounding a decimal number
JavaScript has a very strange approach to decimal numbers:
|
1 2 |
x= 0.1*0.2; console.log(x); // Returns: 0.020000000000000004 |
Due to such unwanted results, it is necessary to round the number.
This function is most similar to rounding from school.
Default behavior
By default this method rounds to the nearest integer:
|
1 2 3 4 5 |
Math.round( 20.49); // 20 Math.round(1.532); // 2 Math.round(1.235); // 1 Math.round(27.94); // 28 Math.round(0.0005); // 0 |
Rounding to a decimal
If we want to round to decimals, we need to use the trick:
|
1 |
Math.round(number * 100) / 100 // for rounding to two decimal places |
Advanced version rounding to decimals
For rounding to a decimal, use the following function that accepts as arguments the number to be rounded and the number of decimals to which we want to round.
|
1 2 3 4 |
function round(value, decimals) { return Number(Math.round(value+'e'+decimals)+'e-'+decimals); } console.log(round(1.55505, 2)); // Returns: 1.56 |
However, this method also has a drawback for the case:
|
1 |
console.log(round(0.00005, 2)); // Returns: 0 |
This method returns the first smaller integer of the provided number
|
1 2 3 4 5 |
Math.floor( 45.95); // 45 Math.floor( 45.05); // 45 Math.floor( 4 ); // 4 Math.floor(-45.05); // -46 Math.floor(-45.95); // -46 |
This method returns the first larger integer of the provided number:
|
1 2 3 4 5 6 |
Math.ceil( 45.95); // 46 Math.ceil( 45.05); // 46 Math.ceil( 4 ); // 4 Math.ceil( 7.05); // 8 Math.ceil(-45.05); // -45 Math.ceil(-45.95); // -45 |
This method returns an integer by removing the decimals:
|
1 2 3 4 5 |
Math.trunc(13.37); // 13 Math.trunc(42.84); // 42 Math.trunc(0.123); // 0 Math.trunc(-0.123); // -0` Math.trunc('-1.123'); // -1 |
Random number generation
|
1 2 3 |
function randomBroj(min,max) { return Math.floor(Math.random()*(max-min+1)+min); } |
Example
|
1 |
randomBroj(1,100); // Returns: random broj u rasponu od 1 do 100 |
Date printing
a) Format: date only
|
1 2 3 4 5 6 7 8 9 10 11 12 |
var trenutniDatum = function(separator){ var today = new Date(); var dd = today.getDate(); var mm = today.getMonth()+1; var yyyy = today.getFullYear(); if(dd<10) {dd='0'+dd;} if(mm<10) {mm='0'+mm;} return (mm+separator+dd+separator+yyyy); }; console.log(trenutniDatum('/')); // Returns: "07/26/2017" console.log(trenutniDatum('-')); // Returns:"07-26-2017" |
b) Format: date and time
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var date = new Date(); function stringDate(date) { var mm = date.getMonth()+1; mm = (mm<10?"0"+mm:mm); var dd = date.getDate(); dd = (dd<10?"0"+dd:dd); var hh = date.getHours(); hh = (hh<10?"0"+hh:hh); var min = date.getMinutes(); min = (min<10?"0"+min:min); return mm+'/'+dd+'/'+date.getFullYear()+" "+hh+":"+min; } console.log(stringDate(date)); // Returns"07/24/2017 17:15" |
c) Format – date with name of day and month
|
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 |
var now = new Date(); var days = new Array('Sunday','Monday','Tuesday','Wednesday','Thursday','Friday','Saturday'); var months = new Array('January','February','March','April','May','June','July','August','September','October','November','December'); var date = ((now.getDate()<10) ? "0" : "")+ now.getDate(); function fourdigits(number) { return (number < 1000) ? number + 1900 : number; } today = days[now.getDay()] + ", " + months[now.getMonth()] + " " + date + ", " + (fourdigits(now.getYear())) ; document.write(today); // Returns: Monday, July 24, 2017 |
Is it a leap year?
|
1 2 3 4 5 6 |
function jePrestupna(year) { return year % 400 === 0 || (year % 100 !== 0 && year % 4 === 0); } console.log(jePrestupna(2015)); // Returns: False console.log(jePrestupna(2016)); // Returns: True |
Prevention of multiple form submissions
See the Pen xXyRwZ by Web programming (@chos) on CodePen.

