Categories
JavaScript Answers

How to Create a File Object in JavaScript?

Sometimes, we want to create a file object without our JavaScript code.

In this article, we’ll look at how to create a file object with JavaScript.

Create a File Object with the File Constructor

We can create a file with the File constructor with JavaScript.

For instance, we can write:

const parts = [
  new Blob(['you construct a file...'], {
    type: 'text/plain'
  }),
  ' Same way as you do with blob',
  new Uint16Array([33])
];

const file = new File(parts, 'sample.txt', {
  lastModified: new Date(2020, 1, 1),
  type: "text/plain"
});

const fr = new FileReader();

fr.onload = (evt) => {
  document.body.innerHTML = `
   <a href="${URL.createObjectURL(file)}" download="${file.name}">download</a>
    <p>file type: ${file.type}</p>
    <p>file last modified: ${new Date(file.lastModified)}</p>
  `
}

fr.readAsText(file);

We create the parts array with the parts of a file.

The first entry of parts is a Blob instance with the file content.

The first argument of Blob is the file content in an array.

The 2nd argument of Blob has the file metadata.

The 2nd and 3rd entries of parts has more file content.

Next, we use the File constructor to create a file object.

The first argument is the file content, which we stored in parts .

The 2nd argument is the file name.

The 3rd argument is some metadata.

Next, we create a FileReader instance so we can read the file contents.

We set the onload property of it to watch when the file loads into memory.

In the callback, we get the file metadata from the file .

And we use URL.createObjectURL with file to create a URL so we can download the file from a link we create by setting it as the value of href .

When we call readAsText with file , the onload method will run.

Now when we click on download, we see the sample.txt file download with the content that we put into parts in the text file.

Conclusion

We can create a file with the File constructor. And then we can read the file with the FileReader object.

Categories
JavaScript Answers

How to Check if a JavaScript Object Property is a Method?

In JavaScript, a method is a JavaScript object property that has a function as its value.

Sometimes, we want to check if an object property is a method.

In this article, we’ll look at how to check if a JavaScript object property is a method.

Use the typeof Operator

We can use the typeof operator to check if an object property is a method.

If an object property is a method, then the typeof operator should return 'function' .

For instance, we can write:

const obj = {
  prop1: 'no',
  prop2() {
    return false;
  }
}

console.log(typeof obj.prop2 === 'function');

to check if obj.prop2 is a method.

If it’s a method, then typeof obj.prop2 should return 'function' .

The console log logs true , so we know obj.prop2 is a method.

If it’s not a method or it doesn’t exist, then typeof obj.prop2 won’t return 'function' .

Conclusion

We can use the typeof operator to check if an object property is a method.

Categories
JavaScript Answers

How to Get the Week of Year of a Given Date in JavaScript?

Sometimes, we want to get the week of the year given a date.

In this article, we’ll look at how to get the week of the year of a given date with JavaScript.

Using Native JavaScript Date Methods

One way to get the week of the year of a given date is to use JavaScript date methods to compute the week of the year of a given date ourselves.

For instance, we can write:

const now = new Date(2021, 3, 1);  
const onejan = new Date(now.getFullYear(), 0, 1);  
const week = Math.ceil((((now.getTime() - onejan.getTime()) / 86400000) + onejan.getDay() + 1) / 7);  
console.log(week)

We have the now date which we want to get the year of the week from.

Then we create the onejan date with which is January 1 of the same year as now .

Then we compute the week of the year by subtracting the timestamps of now and onejan .

And then we divide that by 86400000 to get the number of days difference between the 2 dates.

Then we add the day of the week plus 1 to get the actual number of days difference.

Then we divide that by 7 to get the number of weeks difference.

And we round that number up to the nearest integer with Math.ceil .

Therefore, week is 14.

Use Moment.js

A simpler way to get the week number of the year from a given date is to use moment.js.

To use it, we write:

const now = new Date(2021, 3, 1);  
const week = moment(now).format('W')  
console.log(week)

We pass in the now date to moment to create a moment object.

Then we call format with the 'W' formatting tag to get the week of the year of now .

It rounds down, so week is 13.

Conclusion

We can use JavaScript date methods or use moment.js to get the week of the year.

Categories
JavaScript Answers

How to Return the Index of the Greatest Value in a JavaScript Array?

Sometimes, we want to return the index of the greatest value in a JavaScript array.

In this article, we’ll look at how to return the index of the greater value in a JavaScript array.

Use the Array.prototype.indexOf and Math.max Methods

We can find the index of the greatest value in a JavaScript array with the Math.max and the array’s indexOf method.

For instance, we can write:

const arr = [0, 21, 22, 7];
const index = arr.indexOf(Math.max(...arr));
console.log(index)

We call Math.max with the elements of arr in as arguments by spreading arr into the Math.max method.

This returns the greatest element in arr .

And then we can call arr.indexOf on the greatest element of arr .

And so index is 2, which is the index of value 22 in arr .

Use the Array.prototype.reduce Method

Another way to get the index of the greatest element in an array is to use the JavaScript array’s reduce method.

To use it, we write:

const arr = [0, 21, 22, 7];
const index = arr.reduce((iMax, x, i, arr) => x > arr[iMax] ? i : iMax, 0);
console.log(index)

We call reduce on arr with a callback that has the iMax parameter, which is the index of the greatest value of arr so far.

x is the entry of arr being iterated through.

i is the index of x .

arr is the arr array itself.

We return the index of the greatest element by checking if x is bigger than the current element being recorded as the largest so bar, which is arr[iMax] .

If x is bigger than arr[iMax] , we return i .

Otherwise, we return iMax .

0 is the initial value of the index of the greatest element of arr .

And so index is 2 as we saw in the previous example.

Conclusion

We can use the Math.max and Array.prototype.indexOf or Array.prototype.reduce methods to get the index of the greatest elements in a JavaScript array.

Categories
JavaScript Answers

How to Get HTML Elements with Multiple Classes with JavaScript?

Sometimes, we want to get multiple elements with multiple classes with JavaScript.

In this article, we’ll look at how to get HTML elements with multiple classes with JavaScript.

Get HTML Elements with Both Classes

To get HTML elements with both classes, we can use the getElementsByClassName or querySelectorAll methods.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can get the div with text ‘baz’ by writing:

const list1 = document.getElementsByClassName("class1 class2");  
const list2 = document.querySelectorAll(".class1.class2");  
console.log(list1)  
console.log(list2)

We call getElementsByClassName with 'class1 class2' to get the div with both class1 and class2 present.

Likewise, we can do the same with querySelectorAll by using the “.class1.class2” CSS selector.

Then list1 is the HTMLCollection with the 3rd div.

And list2 is the NodeList with the 3rd div.

Get HTML Elements with At Least One Class

We can get HTML elements with at least one class by using the querySelector method.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(".class1,.class2");  
console.log(list)

We use “.class1,.class2” with querySelectorAll to get elements with class1 or class2 or both as the class.

And so list is a NodeList with all 3 elements.

Get HTML Elements with One Class But Not Both

We can also use querySelector to get HTML elements with one class but not both.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we write:

const list = document.querySelectorAll(".class1:not(.class2),.class2:not(.class1)");  
console.log(list)

We use the :not pseudo-selector to exclude class2 with class1 and class1 with class2 .

So list is a NodeList with the first 2 divs.

Get HTML Elements with None of the Classes or One Class Only

To get all the elements with none of the classes or only one of the classes applied to it, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1),:not(.class2)");  
console.log(list)

And we get all the elements in the page but the div with text baz.

Get HTML Elements with None of the Classes

To get the HTML elements with none of the classes, we can use the :not pseudo-selector again.

For instance, if we have the following HTML:

<div class='class1'>  
  foo  
</div>  
<div class='class2'>  
  bar  
</div>  
<div class='class1 class2'>  
  baz  
</div>

Then we can write:

const list = document.querySelectorAll(":not(.class1):not(.class2)");  
console.log(list)

to select anything but the divs with class1 or class2 .

Conclusion

We can use querySelector to select element with any combinations of the classes applied to an element we want.