Dauris Little
  • About
  • Blogging Lyf
  • Contact
  • Portfolio
“Never be limited by other people’s limited imaginations.” – Dr. Mae Jamison

The ($) and (_) within JavaScript

Friday, 04 October 2019 by Dauris
javascript

The dollar sign ($) and the underscore (_) characters are JavaScript (js) identifiers, which just means that they identify an object in the same way a name would. The objects they identify include things such as variables, functions, properties, events, and objects.

For this reason, these characters are not treated the same way as other special symbols. Instead, JavaScript treats $ and _ as if they were letters of the alphabet.

A js identifier — again, just a name for any object — must start with a lower or upper case letter, underscore (_), or dollar sign ($); subsequent characters can also include digits (0-9). Anywhere that an alphabetic character is allowed in js, 54 possible letters are available: any lowercase letter (a through z), any uppercase letter (A through Z), $ and _.

What is the ($) Identifier

The dollar sign is commonly used as a shortcut to the function document.getElementById(). Because this function is fairly verbose and used frequently in js, the $ has long been used as its alias, and many of the libraries available for use with JavaScript create a $() function that references an element from the DOM if you pass it the id of that element.

There is nothing about $ that requires it to be used this way, however. But it has been the convention, although there is nothing in the language to enforce it.

The dollar sign $ was chosen for the function name by the first of these libraries because it is a short one-character word, and $ was least likely to be used by itself as a function name and therefore the least likely to clash with other code in the page.

Now multiple libraries are providing their own version of the $() function, so many now provide the option to turn off that definition in order to avoid clashes. 

Of course, you don’t need to use a library to be able to use $(). All you need to substitute $() for document.getElementById() is to add a definition of the $() function to your code as follows:

function $(x) {return document.getElementById(x);} 

What about (_) Identifier 

A convention has also developed regarding the use of _, which is frequently used to preface the name of an object’s property or method that is private. This is a quick and easy way to immediately identify a private class member, and it is so widely used, that almost every programmer will recognize it.

This is particularly useful in JavaScript since defining fields as private or public is done without the use of the private and public keywords (at least this is true in the versions of JavaScript used in web browsers — js 2.0 does allow these keywords).

Note that again, as with $, the use of _ is merely a convention and is not enforced by JavaScript itself. As far as js is concerned, $ and _ are just ordinary letters of the alphabet.

Of course, this special treatment of $ and _ applies only within JavaScript itself. When you test for alphabetic characters in the data, they are treated as special characters no different from any of the other special characters.

_$dollar signidentifieridentifiersjavascriptjsunderscore
Read more
  • Published in blog, Javascript
No Comments

The Wonders of Getters & Setters in JS

Monday, 30 September 2019 by Dauris

Okay with the assumption that you are a ” something that reference newbie” and be aware I am probably two years in the game and just now understanding this behind javascript.
So as you may already know ‘Getters’ and ‘Setters’ are common archetypal methods in several other programming languages, specifically more within object-oriented languages like C#, Java, and Objective- C. Solet go ahead and dig right into it.
In most object-oriented languages, ‘Getters’ and ‘Setters’ refer to the properties of a given object. Getters are methods that return the value of that property, and as you may assume setters set them. Now Javascript has many object-oriented features, and this taps into some of those.
The reason they’re a thing and why they exist is a lot more clear in other languages in my personal opinion. So I will go on a tangent briefly so you can understand what I mean and the language of my choice will be Java. Okay, so let’s assume that you want to make some cars. To do that, in java we need a class called “Cars”

class Car {
   private int year;
   private string make;
   private string model;
   private string vin;
   private string color;
}

To make a car, we’d do this 

//create a new car that will be called infiniti
Car infiniti = new Car();

A result, since Infiniti is a car and we said that Cars have a year and a make, we know Infiniti has these.

Don’t worry I will each the code snippet stated above, take note of the word private? That means that only Infiniti knows its year and its make and most importantly, it’s own vin. What this means is that Java, the following would not run and would fail:  

CarJacker someRandomThief = new CarJacker();
someRandomThief.attemptingToGetVin(infiniti.vin);

In JS, you can do that –access the property directly through the dot operator. Now, why on the earth would you want that in a language? Because it makes things easier to maintain, it makes code safer and of course cleaner in the long run. When those properties are private, you can prevent other parts of a program you’re writing from accidentally changing them and weird bugs from showing up. this protecting of properties from outside objects is called encapsulation and is hugely important in OOP. Some would consider this a great feature but it can also be super annoying, because how often do we have variables that we never want any other part of the program to access?

Finally entering into the fray are ‘Getters’ and ‘Setters’. Commonly in Java and other languages as stated before getters and setters methods which allow “outsiders” to access those properties.

class Car {
   private int year;
   private string make;
   private string model;
   private string vin;
   private string color;
   
   public string getVinNumber() {
      //this method returns the vin number of the car
      return vin;
   }
   
   public void setVinNumber(string newVinCreated) {
       //'this' refers to the object itself --Infiniti, etc
       this.vin = newVinCreated;
   }
}

As a result, outside objects can now interact! So if our car thief got lucky, it could instead: 

CarJacker someRandomThief = new CarJacker();
//now we just stole a new car
someRandomThief.attemptingToGetVin(infiniti.getVinNumber());

Now in Java, and the other languages that I know of, ‘getter’ and ‘setter’ are common but not formal: ie, I could call getVinNumber() something as unrelated as UnlessMethodName() and it would still work–but would just be a note helpful name.

I know this was much longer than some of my other posts but it all has a purpose of course. Now within the js you have “get” and “set” doing those things because of the OOP idea of encapsulation and getters and setters, which is a useful idea–and sort of a hard sell in particular in js, where it’s not enforced because you don’t have to declare whether something is private, so it becomes a sort of arbitrary weird layer unless you understand the original intended purpose.

 Ultimately the pattern behind is a thing I dislike about JavaScript — and I’ll be as honest as I can be, I’ve read that documentation so many times before, and even again as I was preparing this post and without much it still makes very little sense to me, and I’ve had a lot more experience since the first time I read it along with a hunk of object-oriented under my belt… and it still is really hard to follow.

In short, get latest() is a means of having things happen when you want the value of latest, and enables that to happen–since you have to have a function or method for things to happen–while still letting you skip the “()” because it’s single value representing a property. 

  • JS has a prototypical inheritance, not class-based. Which is far from the only difference, but a huge one.
  • As with everything, there are differences of opinion and you can still have crazy OOP code, it’s not perfect but that’s the intended purpose.
  • I strongly feel that stuff like Raccoon raccoon = new Raccoon() leads too quickly to semantic satiation and can lead to more bugs and always go for more specific or least different variable names when I can, but anyways.
explainlikeyourefivegetgettersjavascriptjslikeiam5setsetters
Read more
  • Published in blog, Javascript, Like I Am Five
No Comments

UMD & ESM… What the heck is this?

Friday, 20 September 2019 by Dauris
javascriptL module pattern morphology

In the beginning, JS did not have a way to import/export modules. This was a problem for many developers and if you don’t believe then picture this. You’re writing an app in just a single file, I know I know it would be a nightmare.

So as time progress, people of higher intellect than myself attempted to add modularity to javascript. The ones that shouldn’t surprise you is UMD and ESM but there are others of course like CommonJS, Native JS and AMD. There are several others but the two from above are considered some of the big players

I am going to tackle some brief information like syntax, purpose and common behaviors. My goal is to help others that may be confused when dealing with particular issues with modules.

UMD
Universal Module Definition or as referenced UMD.
 – Works on front and back end (hence the name universal).
– Unlike the other modules, UMD is more like a pattern to configure several module systems. Check out other patterns
– UMD is usually used as a fallback module when using bundler like rollup/Webpack

(function (root, factory) {
if (typeof define === "function" && define.amd) {
define(["jquery", "underscore"], factory);
} else if (typeof exports == "object") {
module.exports = factory(require("jquery"), require("underscore"));
} else {
root.Requester = factory(root.$, root._);}}(this, function ($,_) {	//this is where I defined my module implementation	var Requester = {//...};
return Requester;}));  

ESM
ES Module short as ESM. It is javascript’s proposal to implement as standard module system. I am sure many of you have seen this: 
import React from 'react'

  • Works in many modern browsers
  • Tree-shakeable, due to ES6’s static module structure
  • ESM allows bundlers like rollup to remove unnecessary code, allowing sites to ship less code to get faster load 
  • can be called in HTML

<script type="module"> import {func1} from 'my-lib'; func1(); </script> 

Summary
– ESM is the best module format thanks to its simple syntax, async nature, and tree-shakeability.
– UMD works everywhere and usually used as a fallback in case ESM does not work
Thanks for reading, devs! In the future, I plan to write in depth about each module, especially ESM because it is packed with many awesomeness.

esmjavascriptjsmodulesumd
Read more
  • Published in blog, Javascript
No Comments

All rights reserved. 

TOP
This site uses tracking cookies to personalize content and ads. AcceptLearn More