Miscellaneous Javascript Notes

Common Regex:

For checking for a format such as : (856) 999-7777  use regex:   /^\(\d{3}\)\s\d{3}-\d{4}$/

Ternary

Boolean conversions

A number 0, an empty string ""nullundefined, and NaN all become false. Because of that they are called “falsy” values.

Break & Continue

 

For loop:

 

Breaking out of a nest for loop ( named loops ):

Curried Functions

The process of breaking up a multiple parameter function in to multiple single(or more) parameters.

Useful for : If you don’t provide all parameters for a function, it returns a function whose input are the remaining parameters and whose output is the result of the original function.

Useful ways of using Currying:

 

Closures

Closures provide two unique purposes. One is memory management and the other is encapsulation. Currying is an example usage of Closures.

Using closures creates a lexical scope that will store variables within it and are available for subsequent functions that may be returned within a function.

For Encapsulation the same idea exists except that a function that is declared within another function but not directly returned (instead as maybe a property of a returned object instead) will still benefit from being able to access the internal values of the nesting closure function

Closure to count how many times a function to ran

The function initializes a counter and then returns an anonymous function which increments the counter. To be used, a variable must be made that is equal to the containing function and is invoked. Then, the variable created will be invoked in order to increase the count.

Example below:

 

Hoisting

Variable that are defined are brought to the top of the file ( or function  it resides in i.e. IIFE ) but remain undefined until the line where the variable is set.

For example.

function declarations are also hoisted but are set at the time that the interrupter runs. function declarations can be safer for this reason.

When a variable or function is created within another function or IIFE, it is hoisted only to the top of the parent function (function scope) – not the global scope. This only applies when using var as it is function scoped.

const and let are aware of global/function scope but unlike var, const and let are aware of block scope (function,if,for,while loop). Hoisting with const and let only happens to the top of the block it was declared in.

unlike var, const and let do not have any value when hoisted until the actual declaration is reached and will throw an error if trying to be accessed before it’s declaration is reached. var is automatically undefined until it’s declaration is reached and will not throw an error if is tried to be accessed before it is defined/declared.

Strict mode

Enabled by placing ‘use strict’; at the top of a js file.

Strict mode will enforce a few things. One is that a variable must use either var,let or const or it will be considered undefined.

In strict mode, all function parameters must have an unique name. Otherwise, an error will be thrown.

Without strict mode, JavaScript will interpret the last use of the parameters name as the prevailing value.

Strict mode also prevents the ability to delete properties on objects that we shouldn’t be able to delete such as:

 

this and controlling it

this is the object that the function is a property of

Four ways to control this

  1. function constructors and the use of “new”
  2. implicit binding (most common)
  3. explicit binding ( i.e. use of bind(), call() and apply()  )
  4. arrow function to maintain lexical scope of this

 

Misc Notes

Objects i.e. {} can only have properties as string types.

If a property of an object is given another object.. Javascript will turn the object property in to a string of “[object object]”

 

call() and apply() methods

Both are available for any function that is created. call() is another way to call a function and to give it different variables. You can also change the “this” context.

apply() is very similar except that it uses an array [] to input the remaining parameters.

For example:

Copy by value vs reference

If a variable has a primitive type ( number, string, boolean ) and is copied by another variable.. it is copied by value. So if the original variable’s value is changed, the new variable that was made when coping the original will not be changed.

If a non-primitive type is copied – it is by reference. So if a variable is set to an array and another variable is set to that variable.. both will reference that array and if either variable pushes/pops a value out of the array.. both will reflect that same array.

One way to copy an array variable to another variable by value is to do the following:

Comparing two different identical objects (or arrays) will never result in true. One way to check however is to JSON.stringify both and than compare.

Array Constructor

 

 

JSON Notes

Double quotes have to be used , ” “, not single quotes.

All property names ( and on nested object properties ) are strings and so must be wrapped in double quotes. undefined and functions can not be used in JSON

Event Loop

The event loop is a event queue where callbacks are placed to be processed after the main thread of execution is done.

For Example:

3 Ways to Create an Object in Javascript

indexOf Method (String and Array)

Properly add & remove eventListeners

In order to remove an eventListener that was assigned, the handling function must be a named function variable and can not be just a anonymous function.

 

Copy objects and exclude selected properties

source: https://enmascript.com/articles/2019/09/20/two-exceptional-use-cases-for-the-spread-operator-you-may-not-know-of

Object Destructuring and aliasing

Destructuring is a way to extract an objects property upon assignment.

 

String Functions

indexOf(wordToLookFor) – will find the starting position of the wordToLookFor and return the starting index. If nothing is found it will return -1

localeCompare() − Returns a number indicating whether a reference string comes before or after or is the same as the given string in sort order

prototype vs __proto__

 

WordPress REST API and Custom Post Types

In my examples, I will be using a custom post type of “recipes”

In order to get a custom post type to show on the REST API (i.e. https://jmrowe.com/blog/wp-json/wp/v2/recipes ) , two options when using register_post_type can be set.

show_in_rest  (boolean) (optional) Whether to expose this post type in the REST API.

rest_base (string) (optional) The base slug that this post type will use when accessed using the REST API. Default: $post_type

show_in_rest must be set to true

rest_base will be the “base” of the url when calling it in the rest API.  So if nothing is set, the $post_type slug will be used.. i.e. recipes. If rest_base is changed to say “recipes-api” then to call it via the REST api it would look like: https://jmrowe.com/blog/wp-json/wp/v2/recipes-api

Sending the rest_url from WordPress to Javascript

wp_localize_script should be used to send the rest api url to javascript in a portable way such as:

 

Creating new fields in the REST responses

To add more/custom fields in the REST response. A function that does so must be added to the hook “rest_api_init” so..

register_rest_field() is used to register/add the custom field in the rest response

 

A good reference for using nonces in custom REST endpoints: https://viastudio.com/wordpress-rest-api-secure-ajax-calls-custom-endpoints/

One thing to note from this example is that WordPress suggest passing the nonce via the header and not the request content data. So, below is the better way of passing the nonce from js back to WordPress:

 

 

How to lazy load using jQuery

Check the comments in code for explanations. This example relies on jQuery.

 

Connecting a Domain to hosting that are on different providers.

This applies when Domain and Hosting are provided by two different service providers ( i.e. GoDaddy hosting and Namecheap domain )

3 pieces of information are needed from the HOSTING to be put in to the settings on the DOMAIN service provider:
nameserver1 address
nameserver2 address
host IP

The nameserver addresses get put in to the nameserver fields
The host IP is used for the A record. A CNAME record is added to add www to the domain and the value of the CNAME record must be the name that is used for the A record.

Assuming the host IP is 198.71.233.41 it would look like:

Misc notes for WordPress

Proper way to add js variables from php is to use localize script.

An efficient way of doing it:

First register the script at the beginning (main.js as an example).

Then if any variables need to be added from php to js you create a call back for a custom filter:

That will add a js variable admin_ajax_url when the script is finally included. The nonce or any other data could be added as well.

Finally, we check the filter to see if any data has been added to it and if not we do not localize the script:

Body and Post Class

WordPress provides body_class() and post_class() which will provide useful classes on both <body> and the individual post i.e. <article> that will give information to target things like specific post ids etc. The functions are to be used like :

 

in_the_loop()

Useful for determining if the caller is within the loop. So for example, if you added an action to ‘loop_end’ to display something after the last of the loop using a condition with in_the_loop() it will make sure the contents of the action will only execute  if it is within the main posts loop.

Including CSS/Javascript for a shortcode

As long as the styles/scripts are registered.. they can be actually en-queued within the actual short code code so that the script/styles will only actually load when the short code is used.

Conditionally enqueueing scripts/styles in admin area

When adding an action to ‘admin_enqueue_scripts’ to enqueue scripts, $hook is passed in to determine what page in the admin area you are on.

To test if you are on a certain plugin menu page you can create a global variable to check against the $hook.

Example:

 

To help with removing render-blocking resources from javascript files:

 

Rewrite API and when/how to flush_rewrite_rules

The simplest solution is to delete the option that WordPress sets after building the rewrite rules upon the plugins activation and deactivation hooks. This will force WordPress to rebuild the rules that you may have added.

 

Change the placeholder for Add Title field on custom post type:

Custom Excerpt