Categories
JavaScript Tips

JavaScript Tips — Jest Mocks, React Background, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Regex to Check Whether a String Contains Only Numbers

We can use a regex to check if a string has only numbers.

For instance, we can write:

const reg = /^d+$/;

^ matches the string from the beginning, and \d is the digit.

Javascript Filename Naming Convention

JavaScript filename should follow some common conventions.

We should use all lowercase filenames.

Also, we don’t want to use spaces in the filename.

We can optionally use a hyphen as a word separator.

And we may also add a version number in our file name if we have one.

By updating the version number in the file name, we always serve the latest one with the CDN alongside the older version.

Calling a Parent Window Function from an iframe

We can access the parent window with the window.parent property.

So if we want to call a function in the parent window from an iframe, we can write:

<a onclick="parent.foo();" href="#" >click me</a>

foo is a top-level function in the parent window.

Center a Popup Window on the Screen

To center a popup window on the screen, we can do some calculations to center the window and pass that off to the specification string.

For instance, we can write:

const openPopup = (url, title, w, h) => {
  const left = (screen.width / 2) - (w / 2);
  const top = (screen.height / 2) - (h / 2);
  return window.open(url, title, `width=${w}, height=${h}, top=${top}, left=${top}`);
}

We get the left coordinate by using the width divided by 2 minus the width divided by 2 to get the x coordinate of the top left corner.

Likewise, we do the same thing but replace the width with the height to get the y coordinate of the top left corner.

Then we pass those to the specification string and also do the same with the width and height.

Setting a Background Image With React Inline Styles

To set a background image with React inline styles, we can import the image as a module.

Then we can interpolate that into the CSS string for setting the background image.

For instance, we can write:

import Background from '../images/background.png';

const styles = {
  backgroundImage: `url(${Background})`
}

We set the backgroundImage property with the url string with the Background image we imported.

Remove Everything After a Given Character

To remove the part of a string after a given character from a string, we can use the split method.

For instance, we can write:

url.split('?')[0]

Then we get part of the url string before the ? .

A Practical Use for a Closure in JavaScript

Closures are great for hiding private things like variables and functions that we don’t want to expose to the outside.

For instance, we can write:

const obj = (() => {
  const private = () => {
    console.log('hello');
  }

  return {
    public() {
      private();
    }
  }
})();

private is a private function.

And public is a function that’s in obj , so it’s available to code outside.

Get the Real Width and Height of an Image

To get the real width and height of an image, we can use the naturalHeight property to get the real height and naturalWidth to get the real width.

For instance, we can write:

const height = document.querySelector('img').naturalHeight;

and:

const width = document.querySelector('img').naturalWidth;

This is available since HTML5.

Mock an ES6 Module Import Using Jest

To mock an ES6 module import using Jest, we can use the jest.fn() function to mock a function.

For instance, we can write:

logger.js

export const log = (y) => console.log(y)

module.js

import { log } from './logger';

export default (x) => {
  doSomething(x * 2);
}

module.test.js

import module from '../module';
import * as `logger` from '../`logger`';

describe('module test', () => {
  it('logs the double the input', () => {
    dependency.`log` = jest.fn();
    module(2);
    expect(dependency.`log`).toBeCalledWith(4);
  });
});

All we have to do is to call jest.fn to create a mock function.

We imported the whole module, so the members aren’t read-only.

Therefore, we can assign our own mock function to it.

Then we call our module function to test our function and check our results.

Conclusion

We should follow some common file naming conventions for naming JavaScript files.

Also, we can mock functions in Jest with the jest.fn() method.

A popup can be centered on the screen.

We can set a background image by importing it and interpolating it in a CSS string in a React component.

Categories
JavaScript Tips

JavaScript Tips — Function Name, Promises Statuses, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Get the Function Name from Within that Function

We can get the function name from within the function by using the name property.

For instance, we can write:

const foo = () => {
  console.log(foo.name);
}

foo();

Then we should see foo logged.

Load Order of Scripts

If we aren’t loading scripts dynamically or marking them with defer or async , then they’re loaded in the order they’re encountered on the page.

This order applies to both inline and external scripts.

Async scripts are loaded in an unpredictable order asynchronously.

Scripts with defer are load asynchronously, but in the same order that they’re encountered.

This lets us load scripts that depend on each other asynchronously.

Scroll HTML Page to the Given Anchor

We can just set the hash value as the value of location.hash to scroll to the element with the given ID.

For example, we can write:

const scrollTo = (id) => {
  location.hash = `#${id}`;
}

We pass in the ID of the element to scroll to the element with that ID.

Return After Early Resolve or Reject

We need to add a return after the line that resolves or reject early.

For instance, we can write:

`const add = (a, b) => {` return new Promise((resolve, reject) => {
    if (typeof a !== 'number' || typeof b !== 'number') {
      reject("a or b isn't a number");
      return;
    }
    resolve(a + b);
  });
}

We need to add return after the reject call so that the code below it won’t run.

Class vs. Static Method in JavaScript

Class methods are different from static methods in JavaScript.

Class methods have to be called on the instance and can access this , which is the instance of the class.

Static methods are called directly on the class itself and can’t access this .

For instance, if we have:

function Foo(name){
  this.name = name;
}

Foo.prototype.bar = function(){
  console.log(this.name);
}

Then we can call the bar method if we create a new instance of Foo :

const foo = new Foo('mary');
foo.bar();

Then 'mary' should be logged since it’s the value of this.name property which set when instantiating it.

On the other hand, static methods are defined directly as the property of a constructor:

function Foo(){}
Foo.hello = function() {
  console.log('hello');
}

Then we call Foo.hello directly:

Foo.hello();

and 'hello' is logged.

With the class syntax, we can put them all in one place:

class Foo {
  constructor(name) {
    this.name = name;
  }

  bar() {
    console.log(this.name);
  }

  static hello() {
    console.log('hello');
  }
}

bar is a class method and hello is a static method.

Get a Subarray from an Array

We can get a subarray from an array with the slice method.

For instance, we can write:

`const arr = [1, 2, 3, 4, 5];
`const arr2 = arr.slice(1, 4);

Then we get [2, 3, 4] for arr2 . The end index isn’t included.

Preloading Images with JavaScript

To preload images, we can create new img elements with the Image constructor and set the src property of it.

For instance, we can write:

const images = [
  'http://placekitten.com/200/200',
  'http://placekitten.com/201/201',
  'http://placekitten.com/202/202',
]

Then we can write:

for (const image of images) {
  const img = new Image();
  img.src = image;
}

Handling Errors in Promise.all

We can handle errors from Promise.allSettled by checking if there are any Error instances from the result.

For instance, we can write:

const getAll = async (`promises`) => {
  `const results = await Promise.allSettled(promises);
  console.log(result.map(x => s.status));
}`

We get promises , which is an array of promises.

Then we call Promise.allSettled to get the results from the promises.

Finally, we get the status of each promise with the status property.

Conclusion

We can get the name of a function with the name property.

Loading orders of scripts are in the same order that they’re listed on the HTML.

Class and static methods are different.

We can use slice to get a subarray of an array.

Promise.allSettled can get the status of all promises.

Categories
JavaScript Tips

JavaScript Tips — TypeScript Interface Checks, Showing/Hiding Elements, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Meaning of the “at” (@) Prefix on NPM Packages

The @ prefix means that the package is a scoped package.

That means the work with the @ prefix is the namespace of the package.

For instance, @angular/http is has angular as the namespace.

Scoped packages don’t show up in public search.

Many of them are created as private packages.

Write an Inline if Statement in JavaScript

We can write an inline if statement by using the ? in Javascript.

For instance, we can write:

(a < b) ? 'bigger' : 'smaller'

a < b is the boolean expression.

If it’s true , then we return 'bigger' .

Otherwise, we return 'smaller' .

Interface Type Check with Typescript

We can check if an object matches an interface with the in operator.

For instance, we can write:

interface A {
  name: string;
}

Then we can create the following function:

function instanceOfA(object: any): object is A {
  return 'name' in object;
}

We make the return type of instanceOfA object is A . This way, we return whether the object matches an interface.

Then we can call the function as follows:

if (instanceOfA(obj)) {
  //...
}

Handle Newlines in JSON

If we have newline characters in our JavaScript object, then we need to escape them in the JSON string.

Otherwise, we would get an unterminated string literal error.

For instance, instead of writing:

const data = '{ "count" : 1, "foo" : "text\n\n" }';

We write:

const data = '{ "count" : 1, "foo" : "text\n\n" }';

Create an Element with ID

We can create an element with an ID by using the setAttribute method after the createElement method.

For instance, we can write:

const div = document.createElement('div');
div.setAttribute("id", "foo");

Hide or Show Elements with JavaScript

To hide an element we can set the style.display property of an element to 'none' to hide an element.

For instance, we can write:

document.getElementById('foo').style.display = 'none';

to hide the element with ID 'foo' .

If we want to show an element, we can set style.display to 'block' .

So we can write:

document.getElementById('foo').style.display = 'block';

instanceof Return false for Some Literals

If we use instanceof to check the type of primitive literals, we’ll get false for all of them.

For instance, if we have:

"foo" instanceof String

then that will return fale .

Likewise, false instanceof Boolean also returns false .

To check primitive literals for their types, we should use the typeof operator.

For instance, we can write:

typeof str === 'string'

to check if str is a primitive string.

We can do the same for other primitive types like numbers and booleans.

Push Multiple Elements to Array

We cab push multiple items to an array with push .

For instance, we can write:

const arr = [];
arr.push(1, 2, 3);

We call push with 3 numbers and they’ll all be added.

Also, if we have an array, we can use the apply method.

For instance, we can write:

arr.push.apply(arr, [1, 2, 3]);

or:

Array.prototype.push.apply(arr, [1, 2, 3])

To do the same thing.

Also, we can use the spread operator:

arr.push.apply(...[1, 2, 3]);

They all pass in the array entries as arguments.

Make an HTML Back Link

To make an HTML link that goes to the previous URL, we can write:

<a href="javascript:history.back()">Go Back</a>

We call history.back() when the link is clicked to go to the previous page.

Also, we can write:

<a href="#" onclick="history.go(-1)">Go Back</a>

to do the same thing.

Difference Between the currentTarget Property and the target Property

There’s a difference between the currentTarget and the target property because of event bubbling.

target is the element that triggered the event.

currentTarget is the element that the event listener is attached to.

Conclusion

We can make namespaced packages with the @ prefix.

Also, we can call push with more than one argument.

instanceof can’t be used to check primitive values.

Showing and hiding items can be done with JavaScript.

Categories
JavaScript Tips

JavaScript Tips — Radio Button Value, Assertions, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Get the Selected Radio Button’s Value

To get the selected radio button’s value, we can use the checked and value properties.

For instance, if we have the following HTML:

<input type="radio" name="gender" value="female" checked="checked">Female</input>
<input type="radio" name="gender" value="male">Male</input>

We can get the the the radio buttons by name with getElementsByName :

const radios = document.getElementsByName('gender');

for (const radio of radios) {
  if (radio.checked) {
    console.log(radio.value);
  }
}

We loop through the radio buttons retrieved with the for-of loop.

Then we use the checked property to see if it’s checked.

Then we get the value of the value attribute with the value property.

Create Our own assert Function in JavaScript

There’s no assert function in client-side JavaScript.

In Node, there’s the assert module.

To make our own assert function without a library, we can create our own function:

const assert = (condition, message) => {
  if (!condition) {
    throw new Error(message || "Assertion failed");
  }
}

The function only checks if condition is truthy.

If it’s not, then we throw an error with our own message if we like.

Add a New Value to an Existing Array in JavaScript

We can all the push method to add a new value to an existing JavaScript array.

For instance, we can write:

const arr = [];
arr.push('foo');
arr.push('bar');

We can use unshift to add values to the beginning:

const arr = [];
arr.unshift('foo');

We can also set the value by its index directly since JavaScript arrays are dynamically sized:

const array = [];
array[index] = "foo";

How to Check if 2 Arrays are Equal with JavaScript

We can check if 2 arrays are equal with JavaScript by looping through all the entries to see if they’re all equal.

For instance, we can write:

const arraysEqual = (a, b) => {
  if (a === b) { return true; }
  if (a === null || b === null) { return false; }
  if (a.length !== b.length) { return false; }

  for (let i = 0; i < a.length; i++) {
    if (a[i] !== b[i]) {
      return false;
    }
  }
  return true;
}

This works with arrays that only have primitive values because we can’t compare object contents directly with === or !== .

We check if a references the same object as b .

If it’s so, then we return true .

If one or more of them are null , we return false .

If their lengths aren’t equal, we return false .

Then we compare the contents if we get past all those checks.

In the loop body, if any entry aren’t equal to each other, then we return false .

If it goes through the loop without returning false , then all entries are equal so we return true .

If we need to check object contents, then we need to recursively traverse all the properties of the object and check their content.

Turn a string into a JavaScript Function Call

We can pass in the name string to the object with the function that we want to call to call the function.

For instance, we can write:

const fn = obj[functionName];
if (typeof fn === 'function') {
  fn(id);
}

We pass the functionName string into the brackets after obj to and assign the returned value to fn .

Then we use typeof to check if it’s a function.

If it’s a function, then we call it.

Remove Array Element Based on Object Property

To remove an array element based on an object property, we can use the filter method.

For instance, we can write:

arr = arr.filter(obj => obj.name !== 'james');

The code above returns an array with all the entries where the name property isn’t 'james' .

Since it returns a new array, we’ve to assign it to arr to replace its value.

Conclusion

We can use the value property to get the value of the value attribute of a checkbox.

To create an assert function, we can throw an error if a condition isn’t met.

There are methods to add items to an array.

We can compare each entry of an array to see if they’re equal.

Categories
JavaScript Tips

JavaScript Tips — Child Constructors, Text Selection, Inline Workers, and More

Like any kind of apps, there are difficult issues to solve when we write JavaScript apps.

In this article, we’ll look at some solutions to common JavaScript problems.

Prevent Text Selection After Double Click

We can stop text selection after a double click by calling preventDefault() to stop the default action.

For example, we can write:

document.addEventListener('mousedown', (event) => {
  if (event.detail > 1) {
    event.preventDefault();
    // ...
  }
}, false);

Why is it Necessary to Set the Prototype Constructor?

We’ve to set the prototype constructor so that we can check with instanceof that the prototype’s constructor is a given constructor.

For instance, if we have:

function Person(name) {
  this.name = name;
}


function Student(name) {
  Person.call(this, name);
}

Student.prototype = Object.create(Person.prototype);

Then the Student ‘s prototype is set to Person .

But we actually want to set it to Student , even though it inherits from Person .

Therefore, we need to write:

Student.prototype.constructor = Student;

Now if we create an instance of Student , and check if it with instanceof :

student instanceof Student

Then that would return true .

If we use the class syntax, then we don’t have to do that anymore.

We just write:

class Student extends Person {
}

and everything else is handled for us.

Creating Web Workers without a Separate Javascript File

We can create a web worker without creating a separate JavaScript file using the javascript/worker as the value of the type attribute.

For instance, we can write:

<script id="worker" type="javascript/worker">
  self.onmessage = (e) => {
    self.postMessage('msg');
  };
</script>
<script>
  const `blob = new Blob([
    document.querySelector('#worker').textContent
  ];`

  const worker = new Worker(window.URL.createObjectURL(blob));
  worker.onmessage = (e) => {
    console.log(e.data);
  }
  worker.postMessage("hello");
</script>

We get the worker as a blob by using get the script element and use the textContent property on it.

Then we create the worker with the Worker constructor with the blob.

Then we write our usual worker code in the worker and the script invoking the worker.

How to Trim a File Extension from a String

We can trim the file extension from a string, we can use replace method.

For instance, we can write:

fileName.replace(/\.[^/.]+$/, "");

We get the last part of the string that’s after the dot with the regex pattern.

And we replace it with the empty string.

In Node apps, we can use the path module.

To get the name, we can write:

const path = require('path');
const filename = 'foo.txt';
path.parse(filename).name;

path.parse takes the file path. Then we get the name property from it.

Why does parseInt Return NaN with Array.prototype.map?

parseInt returns NaN with array instance’s map method because parseInt takes arguments but the map callback takes 3 arguments.

parseInt takes the number as the first argument and the radix as the 2nd argument.

The map callback takes the array entry as the first argument, index as the 2nd argument, and the array itself as the 3rd argument.

Therefore, if we use parseInt directly as the callback, then the index will be passed in as the radix, which doesn’t make sense.

This is why we may get NaN .

We get that if the radix isn’t a valid radix.

Therefore, instead of writing:

['1','2','3'].map(parseInt)

We write:

['1','2','3'].map(Number)

or:

['1','2','3'].map(num => parseInt(num, 10))

Omitting the Second Expression When Using the Ternary Operator

If we have the following ternary expressions:

x === 1 ? doSomething() : doSomethingElse();

but we don’t want to call doSomethingElse when x === 1 is false , then we can use the && operator instead.

For instance, we can write:

x === 1 && dosomething();

Then if x === 1 is true , then doSomething is called.

Clear Cache in Yarn

We can clear the cache in yarn by using the yarn cache clean command.

innerText Works in IE, but not in Other Browsers

innerText is an IE-only property for populate texting content of a node.

To do the same thing other browsers, we set the textContent property.

For instance, we write:

const el = document.`getElementById`('foo');
el.textContent = 'foo';

Conclusion

We can stop selection after double-clicking by calling preventDefault to stop the default action from running.

Also, we shouldn’t use parseInt as a callback for map .

We’ve to set the constructor to the current constructor if we create a child constructor.

This way, we can check for the instance properly.