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.