Tag: JavaScript

JavaScript: how to check if a string variable is an integer value

JS on yellow background

One way to check if a variable is of type integer, Number.isInteger() can be used:

JavaScript
Number.isInteger(22); // true
Number.isInteger(22.2); // false
Number.isInteger('22'); // false

But this solution has the disadvantage, that a string with integer value like '22' will result in false.

To address this case, another solution is required:

JavaScript
function isInteger(data) {
  return +data === parseInt(data);
}

isInteger(22); // true
isInteger(22.2); // false
isInteger('22'); // true

This will result in true for integer 22 as well as a string '22'.

 

JavaScript: the differences between escape(), encodeURI(), and encodeURIComponent()

minimized programming code

In JavaScript, escape(), encodeURI(), and encodeURIComponent() are three functions used to encode strings for different purposes. Each function serves a distinct purpose, and it’s essential to understand their differences:

escape()

The escape() function is used to encode a string so that it can be safely included in a URL query string. It encodes special characters, except for alphanumeric characters and the following set of symbols: @*_+-./. The main drawback of escape() is that it does not encode all characters, and it’s considered deprecated in favor of encodeURIComponent().

Example:

const originalString = "Hello, World!";
const encodedString = escape(originalString);
console.log(encodedString); // "Hello%2C%20World%21"

encodeURI()

The encodeURI() function is used to encode a complete URI (Uniform Resource Identifier) but leaves the special characters used in the query string (?, &, =, etc.) untouched. It is primarily used to encode the main part of a URL, such as the protocol, domain, and path.

Example:

const originalURI = "https://www.example.com/my page.html?name=John Doe";
const encodedURI = encodeURI(originalURI);
console.log(encodedURI); // "https://www.example.com/my%20page.html?name=John%20Doe"

encodeURIComponent()

The encodeURIComponent() function is used to encode a component of a URI, such as a query parameter, fragment identifier, or any part that needs to be included in the query string. Unlike encodeURI(), this function encodes all special characters to ensure they are safely passed as parameters in a URL.

Example:

const originalParameter = "John Doe";
const encodedParameter = encodeURIComponent(originalParameter);
console.log(encodedParameter); // "John%20Doe"

In summary

Use escape() for encoding a string to be safely included in a query string, but it’s deprecated and not recommended for general use.

Use encodeURI() for encoding a complete URI (protocol, domain, path) but not the query string parameters.

Use encodeURIComponent() for encoding individual components (e.g., query parameters) of a URI to ensure all special characters are encoded properly. This is the most commonly used encoding function for URLs.

Foto von Markus Spiske auf Unsplash

 

jQuery methods in plain JavaScript

cup of coffee

Life is already very complex, so let’s simplify your projects by removing all the jQuery code. Plain JavaScript provides the same functionalities and it does not require any additional frameworks. And it’s supported by most of the modern browsers out of the box. This is a list of replacements for your daily used jQuery methods.

$() or jQuery()

Return a collection of matched elements either found in the DOM based on passed argument(s) or created by passing an HTML string.

// jQuery implementation
var element = $(selector);
// Plain JavaScript
var element = document.querySelector(selector); // Single element
var elements = document.querySelectorAll(selector); // Multiple elements

.addClass()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.addClass('text-bold');
// Plain JavaScript
element.classList.add('text-bold');

.attr()

Adds the specified class(es) to each element in the set of matched elements.

// jQuery implementation
element.attr(attribute, value);
// Plain JavaScript
element.setAttribute(attribute, value);

.css()

Set one or more CSS properties for the set of matched elements.

// jQuery implementation
element.css(property, value);
// Plain JavaScript
element.style[property] = value;

.each()

Iterate over a jQuery object, executing a function for each matched element.

// jQuery implementation
$.each(settings, function (index, element) {
    // ...
});
// Plain JavaScript
settings.forEach((element, index) => {
    // ...
});

.empty()

Remove all child nodes of the set of matched elements from the DOM.

// jQuery implementation
container.empty();
// Plain JavaScript
container.replaceChildren();

See https://stackoverflow.com/a/65413839/768352

.extend()

Merge the contents of two or more objects together into the first object.

// jQuery implementation
const settings = $.extend(defaults, options)
// Plain JavaScript
const settings = {...defaults, ...options}

.hasClass()

Determine whether any of the matched elements are assigned the given class.

// jQuery implementation
if (element.hasClass('text-bold')) {
  // ...
}
// Plain JavaScript
if (element.classList.contains('text-bold')) {
  // ...
}

.hide()

Hide the matched elements.

// jQuery implementation
element.hide();
// Plain JavaScript
element.style.display = 'none';

.html()

Set the HTML contents of each element in the set of matched elements.

// jQuery implementation
element.html('<div>my html</div>');
// Plain JavaScript
element.style.innerHTML = '<div>my html</div>';

.map()

Translate all items in an array or object to new array of items.

// jQuery implementation
$.map(array, function (value, index) {});
// Plain JavaScript
array.map((value, index) => {});

.now()

Return a number representing the current time.

// jQuery implementation
$.now();
// Plain JavaScript
Date.now();

.removeClass()

Remove a single class or multiple classes from each element in the set of matched elements.

// jQuery implementation
element.removeClass('text-bold');
// Plain JavaScript
element.classList.remove('text-bold');

.show()

Display the matched elements.

// jQuery implementation
element.show();
// Plain JavaScript
element.style.display = 'block';

.text()

Set the content of each element in the set of matched elements to the specified text.

// jQuery implementation
element.text('my text');
// Plain JavaScript
element.textContent = 'my text';

.toggle()

Display or hide the matched elements.

// jQuery implementation
element.toggle();
// Plain JavaScript
element.style.display = element.style.display === 'none' ? 'block' : 'none';

.toggleClass()

Add or remove one or more classes from each element in the set of matched elements, depending on either the class’s presence or the value of the state argument.

// jQuery implementation
element.toggleClass('text-bold');
// Plain JavaScript
element.classList.toggle('text-bold');

.trigger()

Execute all handlers and behaviors attached to the matched elements for the given event type.

// jQuery implementation
$(document).trigger("myEvent");
$(".container").trigger("myEvent");

// Plain JavaScript
document.dispatchEvent(new Event("myEvent"));
document.querySelector(".container").dispatchEvent(new Event("myEvent"));

.val()

Get the current value of the first element in the set of matched elements.

// jQuery implementation
var val = element.val();
// Plain JavaScript
var val = element.value;

Photo by Jakub Dziubak on Unsplash

JavaScript: simple code structure for libraries

macbook pro on a table

The code of a JavaScript library might get very complex over time. This can be a problem for maintenance and expandability.

When writing a library, you should address two main points:

  • Keep the environment clean from global variables and methods to avoid conflicts between different libraries
  • Provide public and private methods and variables

The following “template” provides a simple code structure that fulfills those points:

// Unique name of the library.
MyLibrary = function() {
  MyLibrary = {};

  /*
   * Internal variables and methods
   */
  var variable = 'value';
  function doSomething() {
    // do something
  }

  /*
   * Public variables and methods
   */
  MyLibrary.myVariable = true;
  MyLibrary.myAction = function() {
    // do something
  }

  // Return the library.
  return MyLibrary;
}

You can use such a library the following way:

const lib = MyLibrary();
lib.myAction()

if (lib.myVariable) {
  alert('really?');
}

Inspiration: https://stackoverflow.com/questions/13606188/writing-a-library-what-structure

Photo by Safar Safarov on Unsplash

Which programming language is the best one?

street sign "dead end"

Is it really possible to answer this question?

Yes, the correct answer is: all of them. Or let’s ask another question first: for which problem?

There is not “the one and only” best programming language, there are tons. This question is simply not a good one. It’s good for endless discussion, but it’s neither complete, nor does it give you details about the problem to solve. An answer will not solve the unknown problem of the author. Every coding language has it advantages when it comes to solving a specific problem. But which one? There are advantages for JavaScript, Python, PHP, Java, Swift, Dart and others. But what if the author wants to write some firmware for a micro controller? Ok, you see the point.

But why do people ask those questions?

I see a lot of such questions posted on all social platforms. And as those questions are so incomplete, there are no correct answers. The results are endless discussions about the advantages of each coding language. And this is what most of the authors want: an open question which leads to endless attention. In detail: likes and retweets to pretend the algorithms to be an interesting account. Honestly, no one reads through thousands of responses. And if yes, you only see the advantages that each comfortable developer or user sees in his area of expertise. This might lead to some short attention, but it will never create some high quality and valuable content fo the users. And that’s a pity.

And what about: iOS or Android? Windows or macOS? Python or JavaScript? Same thing! The answers are just a time wasting mess.

Photo by Donald Giannatti on Unsplash.