Categories
JavaScript Answers

How to Access the First Property of a JavaScript Object?

In our JavaScript programs, sometimes we only want to access the first property of a JavaScript object.

In this article,e we’ll look at various ways we can access only the first property of a JavaScript object.

Object.keys

The Object.keys method returns an array with the string keys of an object.

So we can access the first property in an object by writing:

const obj = {
  a: 1,
  b: 2
};
const [prop] = Object.keys(obj)
console.log(obj[prop])

We have the obj object with some properties.

And we call Object.keys and destructure the first key from the returned array and assign it to prop .

And then we get the value of the first property returned with obj[prop] .

So we get 1 from the console log.

for-in Loop and break

We can use the for-in loop to loop through an object and break after the first iteration.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

for (const prop in obj) {
  console.log(obj[prop])
  break;
}

We have the for-in loop and log the first property value returned.

prop has the property key string.

Then we use break to stop iterating.

Object.values

We can use the Object.values method to get the values from an object.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [value] = Object.values(obj)
console.log(value)

If we just want the first property value, then we can just use Object.values and destructure it from the returned array.

Object.entries

We can use the Object.entries method to return an array of arrays of key-value pairs.

For instance, we can write:

const obj = {
  a: 1,
  b: 2
};

const [
  [key, value]
] = Object.entries(obj)
console.log(key, value)

to get the first key-value pair from the returned array.

We just destructure it from the nested array.

And so key is 'a' and value is 1.

Conclusion

We can use JavaScript object static methods or the for-in loop to get the first property from a JavaScript object.

Categories
JavaScript Answers

How to Check Whether a JavaScript Object is a Date Object?

Sometimes, we’ve to check if a JavaScript object is a date object.

In this article, we’ll look at ways to check whether a JavaScript object is a date object.

Checking for Methods that Date Objects Have

We can check for methods that date objects have.

To do this, we can use the typeof operator.

For instance, we can write:

const date = new Date(2021, 1, 1);
console.log(typeof date.getMonth === 'function')

We check that the getMonth method is a function by using the typeof operator to see if it returns 'function' .

If it’s true , then we know it’s likely that date is a Date instance.

The console log should log true , so it’s a good chance that it’s a Date instance.

The instanceof Operator

A more accurate check is to check whether the object is created from the Date constructor.

If it is, then we know it must be a Date instance.

For instance, we can write:

const date = new Date(2021, 1, 1);
console.log(date instanceof Date)

to check if date is created from the Date constructor with the instanceof operator.

The left operand is the object we’re checking.

And the right operand is the constructor we’re checking for.

Since date is created from Date , the console log should log true .

To check if an object is created from the Date constructor across frame boundaries, we can convert it to a string with the toString method and check its contents.

To do this, we write:

const date = new Date(2021, 1, 1);
console.log(Object.prototype.toString.call(date) === '[object Date]')

We call toString as Object.prototype.toString.call since toString maybe overridden with our own methods.

By calling it this way, we make sure we call the built-in toString method rather than the one we created.

Check for Invalid Date

If we pass in something that can’t be parsed to a date into the Date constructor, then it returned 'Invalid Date' when the object is converted to a string.

So we can check for this by writing:

console.log(new Date('abc').toString() === 'Invalid Date')

We pass in 'abc' into the Date constructor, which can’t be parsed to a date.

So when we call toString , it returns ‘Invalid Date’ .

Therefore, the console log should log true .

Conclusion

There’re several ways we can use to check for a valid date object or an invalid one with JavaScript.

Categories
JavaScript Answers

How to Subtract Days from a JavaScript Date?

Subtract dates from a date is an operation that we’ve to do often in our JavaScript code.

In this article, we’ll look at how to subtract days from a JavaScript date.

Date.prototype.getDate and Date.prototype.setDate

We can use the getDate method to get the date.

And then use the setDate method to set the date by manipulating the date we got from getDate and passing the returned value into setDate .

For instance, we can write:

const date = new Date(2021, 1, 1);
date.setDate(date.getDate() - 5);
console.log(date)

to subtract 5 days from February 1, 2021.

We call getDate from the date object.

Then we subtract 5 days from it.

And then we pass that into setDate .

Therefore date is now 'Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)’ .

date is changed in place with setDate .

Date.prototype.getTime and Date.prototype.setTime

We can also call setTime to set the timestamp of the date instead of the days.

This is more precise since the time is in milliseconds.

To do this, we write:

const dateOffset = (24 * 60 * 60 * 1000) * 5;
const date = new Date(2021, 1, 1);
date.setTime(date.getTime() - dateOffset);
console.log(date)

We have the dateOffset in milliseconds.

And we have the same date object as in the previous example.

In the 3rd line, we call setTime with the timestamp value returned from getTime , which is in milliseconds.

And we subtract that by dateOffset , which is 5 days in milliseconds.

date is changed in place with setTime .

So date in string form is now ‘Wed Jan 27 2021 00:00:00 GMT-0800 (Pacific Standard Time)' .

moment.js

We can use the moment.js library to make date manipulation easier.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(dateMnsFive.toDate())

We create a moment object for February 1, 2021 with moment .

The returned object has the subtract method to let us subtract the time amount we want.

The first argument is the amount.

And the 2nd argument is the unit of the amount to subtract from.

Then we can convert that back to a native JavaScript date object with toDate .

And so we get the same result as the previous examples.

Moment objects also come with the toISOString method.

For instance, we can write:

const dateMnsFive = moment('2021-02-01').subtract(5, 'day');
console.log(new Date(dateMnsFive.toISOString()))

We can pass in the string returned by toISOString to the Date constructor to get a native date object back.

And so we get the same result as the previous example.

Conclusion

We can subtract days from a date with native JavaScript date methods.

To make the work easier, we can also use a library like moment.js to help us.

Categories
JavaScript Answers

How to Get the User’s Time Zone and Offset in JavaScript?

Sometimes, we need to get the user’s time zone in our JavaScript web app.

In this article, we’ll look at how to get the user’s time zone and offset in JavaScript.

Date.prototype.getTimezoneOffset

JavaScript’s native Date objects has the getTimezoneOffset method that returns the user’s time zone.

To use it, we can write:

const offset = new Date().getTimezoneOffset();  
console.log(offset);

It returns the difference between UTC and local time.

So we see that offset is 480 if we’re in the Pacific Standard Time.

The offset is positive when it’s behind UTC and negative otherwise.

The offset is in minutes so we divide it by 60 to get the number of hours.

Daylight saving time prevents this value from being constant.

The Intl.DateTimeFormat Constructor

Also, we can use theIntl.DateTimeFormat().resolvedOptions().timeZone property to get the user’s time zone.

For instance, if we have:

console.log(Intl.DateTimeFormat().resolvedOptions().timeZone)

Then if we’re in the Pacific Time Zone, we may get something like:

'America/Los_Angeles'

returned.

Extract the Time Zone from the Date String

We can extract the time zone from the string returned from the toString method from a JavaScript native Date instance.

For instance, we can write:

const split = new Date().toString().split(" ");  
const timeZone = split.slice(-3).join(' ')  
console.log(timeZone)

And timeZone should be ‘(Pacific Standard Time)’ if we’re in the Pacific Standard Time time zone.

We split the date string returned from toString by a space with split .

Then we call slice with -3 to get the last 3 parts of the string.

And we join them together with join .

To make the extract easier, we can use a regex object.

For instance, we can write:

const [timeZone] = new Date().toString().match(/([A-Z]+[+-][0-9]+.*)/)  
console.log(timeZone)

to get the part of the date string with the upper case letters, plus or minus sign, the digits, and the time zone name together.

We call match on it to get the match.

It returns an object, so we can destructure the result and assign it to timeZone .

And so timeZone is:

'GMT-0800 (Pacific Standard Time)'

We can extract the letters and digits part only by writing:

const [timeZone] = new Date().toString().match(/([A-Z]+[+-][0-9]+)/)  
console.log(timeZone)

And we get 'GMT-0800' for timeZone .

We can extract the text in parentheses with:

const [timeZone] = new Date().toString().match(/(([A-Za-zs].*))/)  
console.log(timeZone)

And timeZone would be ‘(Pacific Standard Time)‘.

Also, we can extract the hours’ difference from UTC by writing:

const [timeZone] = new Date().toString().match(/([-+][0-9]+)s/)  
console.log(timeZone)

And we get '-0800' if we’re in the Pacific Standard Time time zone.

Conclusion

We can get the user’s time zone in multiple ways with JavaScript.

We can extract the items from a date string or we can use a library to built-in methods to extract them.

Categories
JavaScript Answers

Does JavaScript Guarantee Object Property Order?

JavaScript objects are dynamic.

And so we can insert any property into it at any time.

In this article, we’ll see if JavaScript objects have a guaranteed order for sorting properties.

ES2015 Objects

In ES2015, the order mostly follows the insertion order.

This is true expect and some keys are numbers.

If there’s a mix of numeric and non-numeric keys, then the numeric keys are traversed first.

Then the other keys are traversed.

The behavior for numeric keys can vary between browsers.

Chromium doesn’t respect the insertion order for numeric keys and put them first for example.

For instance, if we have the following object:

const obj = Object.create(null, {
  m: {
    value() {},
    enumerable: true
  },
  "2": {
    value: "2",
    enumerable: true
  },
  "b": {
    value: "b",
    enumerable: true
  },
  0: {
    value: 0,
    enumerable: true
  },
  [Symbol()]: {
    value: "sym",
    enumerable: true
  },
  "1": {
    value: "1",
    enumerable: true
  },
  "a": {
    value: "a",
    enumerable: true
  },
});

for (const prop in obj) {
  console.log(prop)
}

When we loop through it with the for-in loop, we see that we get:

0
1
2
m
b
a

logged.

The numeric keys came first.

Then the non-numeric string keys are loop through in their order that they’re inserted.

The following methods guarantee to traverse the keys in the order in that they’re inserted:

  • Object.assign
  • Object.defineProperties
  • Object.getOwnPropertyNames
  • Object.getOwnPropertySymbols
  • Reflect.ownKeys

But these methods or loops don’t guarantee to traverse objects in any order:

  • Object.keys
  • for..in
  • JSON.parse
  • JSON.stringify

However, we can sort the keys if we use Object.keys since the keys are returned in an array.

Before ES2015

Before ES2015, the iteration order of object keys isn’t defined.

This means that they can vary between different runtime environments.

However, most of them follow the same rules as in ES2015.

Conclusion

There’s no guarantee that object properties are traversed in any order in JavaScript objects.

Therefore, we should sort them or use JavaScript maps if we want to guarantee that keys are traversed in the order we want.