Categories
JavaScript Answers

How to Convert a JavaScript Array into a String?

One way to convert a JavaScript array into a string is to concatenate an empty string after it.

For instance, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr + ""
console.log(str)

Then str is:

'Sunday,Monday,Tuesday,Wednesday,Thursday'

Use the Array.prototype.toString Method

Another way to convert a JavaScript array into a string is to use the JavaScript array toString method.

For example, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr.toString();
console.log(str)

Then we get the same result as before.

Use the Array.prototype.join Method

Another way to convert a JavaScript array into a string is to use the JavaScript array join method.

We pass in a delimiter to join the strings in the array with and it’ll return a stirring with all the string array entries joined together.

For example, we can write:

const arr = ['Sunday', 'Monday', 'Tuesday', 'Wednesday', 'Thursday']
const str = arr.join(", ");
console.log(str)

And str is:

'Sunday, Monday, Tuesday, Wednesday, Thursday'
Categories
JavaScript Answers

How to Set Boolean Values in JavaScript LocalStorage?

We can only store strings as values in local storage.

Therefore, boolean values are converted to strings.

To check for them, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(JSON.parse(value) === true);

We call setItem to store a boolean value with the 'value' key.

Then we get the item with the 'value' key with getItem .

Next, we call JSON.parse to parse that value back into a boolean.

And we check that value with === to see if it equals to true exactly.

The console log logs true so we know value is parsed as true .

We can also check the string directly.

For instance, we can write:

localStorage.setItem('value', true)  
const value = localStorage.getItem('value');  
console.log(value === 'true');

to compare value with 'true' with === .

And we also get true logged.

Categories
JavaScript Answers

How to Calculate the Day of the Year with JavaScript?

We can calculate the day of the year with JavaScript with some native date methods.

For instance, we can write:

const now = new Date(2021, 11, 3);
const start = new Date(2021, 0, 0);
const diff = (now - start) + ((start.getTimezoneOffset() - now.getTimezoneOffset()) * 60 * 1000);
const oneDay = 1000 * 60 * 60 * 24;
const day = Math.floor(diff / oneDay);
console.log(day);

We have the now and start date where now is the date we want to calculate the difference from start .

Then we calculate the diff difference by subtract now from start and add the time zone offsets differences to correct discrepancies because of time zone differences.

Next, we calculate the number of milliseconds in a day with the oneDay variable.

Next, we calculate the number of days difference between now and start by dividing diff with oneDay and then take the floor of the quotient with Math.floor .

And then we log the day result.

day should be 337 according to the console log.

Categories
Vue Answers

How to Share a Method Between Components in Vue?

Sometimes, we want to share methods between components in our Vue project.

In this article, we’ll look at how to share methods between components in our Vue project.

Share a Method Between Components in Vue

To share a method between components in Vue, we can create a module that exports the method.

For instance, we can write:

src/shared.js

export default {
  bar() {
    alert("bar")
  }
}

Then we can use it in our component by writing:

src/App.js

<template>...</template>

<script>
import shared from './shared'

export default {
  created() {
    shared.bar();
  }
}
</script>

We imported the shared module and called the bar method inside it.

Alternatively, we can create a mixin, which is a piece of code that can be merged into our component.

For instance, we can write:

const cartMixin = {
  methods: {
    addToCart(product) {
      this.cart.push(product);
    }
  }
};

Then we can use it in our component by writing:

const Store = Vue.extend({
  template: '#app',
  mixins: [cartMixin],
  data(){
    return {
      cart: []
    }
  }
})

We call Vue.extend to create a subclass of the Vue constructor.

We can then make a new instance of Store and render that in our app.

Conclusion

To share a method between components in Vue, we can create a module that exports the method.

Categories
Vue Answers

How Rerun Vue Component mounted() Method in a Vue Component?

Sometimes, we want to rerun the code in the Vue component’s mounted method.

In this article, we’ll look at how to rerun the code in the Vue component’s mounted method.

Rerun Vue Component mounted() Method

To rerun the code that we wrote in the mounted method, we can move the code into its own method.

Then we can call that in mounted or anywhere else.

For instance, we can write:

new Vue({
  methods: {
    init(){
      //...
    }
  },
  mounted(){
    this.init();
  }
})

Then we can write:

<button @click="init">reset</button>

We set the init method as the click handler and also run it in the mounted hook.

Now we can reuse it as we wish.

Conclusion

To rerun the code that we wrote in the mounted method, we can move the code into its own method.