Categories
JavaScript Tips

JavaScript Tips — Read Files, UNIX Epochs, Variables, and More

Spread the love

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.

How to get Time in Milliseconds Since the UNIX Epoch

To get the time in milliseconds since the UNIX epoch, which is the time since Jan 1, 1970, 12 AM UTC, we can use Date.now() .

For instance, we can write:

const now = Date.now();

and now is the UNIX timestamp in milliseconds.

We can also write:

const now = new Date().valueOf()

to get the same thing.

Dynamically Create CSS Class in JavaScript and Apply it

To create a dynamic CSS class and apply the class to an element, we can create a style element with JavaScript.

Then we can set the className property of the element to apply the class.

For example, we can write:

const style = document.createElement('style');  
style.type = 'text/css';  
style.innerHTML = '.cssClass { color: green; }';  
document.head.appendChild(style);  
document.getElementById('foo').className = 'cssClass';

We create the style element with type attribute set to 'text/css' .

Then we set the text inside the style element with the innerHTML .

Then we get the head with document.head and append the style element to it.

Finally, we set the className to the one we just created.

Rename Key of a JavaScript Object

To rename a key of a JavaScript object, we can add the new key with the value of the old key.

Then we can delete the old key.

We can use Object.assign to do that.

For instance, we can write:

delete Object.assign(o, { [newKey]: o[oldKey] })[oldKey];

We populate the newKey with the bracket notation.

Then we delete the oldKey with the brackets.

Get Data from fs.readFile

We can get data from the fs.readFile by getting them from the data from the callback.

For instance, we can write:

const fs = require('fs');  
  
fs.readFile('./foo.txt', (err, data) => {  
  if (err) {  
    throw err;  
  }  
  console.log(data);  
});

We can also do it synchronously with readFileSync :

const text = fs.readFileSync('foo.txt','utf8')  
console.log (text)

We pass in the path of the file in both examples.

In the 2nd example, we pass in the encoding of the file.

Detect HTTP or HTTPS then force HTTPS in JavaScript

We can check if a URL starts with https , then we can call location.replace to replace the URL to replace it with the https version of the URL.

For instance, we can write:

if (location.protocol !== 'https:') {  
     location.replace(`https:${location.href.substring(location.protocol.length)}`);  
}

We call location.replace and replace the current URL with the https version.

We call substring to remove the http from the original URL.

Getting JavaScript Object Key List

We can get the object key list with the Object.keys method.

For instance, we can write:

const obj = {  
  foo: 1,  
  bar: 2,   
  baz: 3  
}  
const keys = Object.keys(obj);

Now keys have the keys of obj .

Use the onClick Listener to get the ID of the Clicked Button

We can get the ID of the element that’s clicked by using this .

For instance, we can write:

<button id="foo" onClick="onClick(this.id)">button</button>

Then we can write:

const onClick = (clickedId) =>  {  
  console.log(clickedId);  
}

Also, we can get the event object’s target property by writing:

const onClick = (event) =>  {  
  console.log(event.target.id);  
}

Difference Between Variable Declaration Syntaxes in Javascript

There are multiple ways to declare variables.

One way is to use var , which creates a global variable of the global object if it’s at the top level.

Otherwise, it’s function scoped.

For instance, we can write:

var x = 1;

let creates a variable in the block scope.

It’s only available within the block and nested blocks.

For instance, we can write:

let foo = 1;

Then we create a block-scoped variable.

const is also block-scoped, but it’s constant. So we can only assign a value to it once when we declare it.

For instance, we can write:

const bar = 1;

Them we can’t assign it another value after this line.

To create global variables, we can create a new property on the window object.

For instance, we can write:

window.a = 0;

Then we attach the a property to the window object.

And we can access it as a .

We should declare block-scoped variables whenever we can to avoid any confusion.

Conclusion

There are many ways to declare JavaScript variables.

We should use block-scoped variables whenever we can.

Style elements can be dynamically added.

There are a few ways to read files in Node apps.

By John Au-Yeung

Web developer specializing in React, Vue, and front end development.

Leave a Reply

Your email address will not be published. Required fields are marked *