what is at() method in JavaScript? [duplicate] - javascript

This question already has answers here:
Using Array.at(index) instead of Array[index] in JavaScript
(4 answers)
Closed last year.
Array.prototype.at()
what is .at() method in JavaScript?
const myList = ['index0', 'index1', 'index2']
myList.at(1) // 'index1'
mylist.at(-1) // 'index2'
there are many methods in js that similarly do this, why using this new method?

Yes, there are similar ways to get an element from an array or string, but at() will use a clear and easy syntax to get this.
give an index and return value
the principle is easy, just put your desire index and get value, if there isn't a value at this index, it returns undefined
for examples:
const myList = ['index0', 'index1', 'index2']
// to get latest item in the list using common ways:
const latestItem = myList[ myList.length - 1]
// using simpler approach with at()
const latestItem = myList.at(-1)
similarly, at() method will work fine with strings.
at the writing time of this post, at() will not be supported by some browser, you can find this here.
you can use polyfill if you want to use at() method in your codebase.

Related

checking if an element is an object in javascript [duplicate]

This question already has answers here:
Check if a value is an object in JavaScript
(54 answers)
Closed 1 year ago.
I am using the following code to check if an element is an object in javascript:
element.constructor == Object Is this a correct way or there are more appropriate ways
to check that? An alternate would be to use this - typeof element === 'object'
There seem to be multiple ways to do that not sure which one is more appropriate
It would be the easiest if you use the lodash package. Lodash is quite common in the js community and I really can recommend this in most cases.
A modern JavaScript utility library delivering modularity, performance & extras.
Lodash docs of isObject function: https://lodash.com/docs/4.17.15#isObject
Checks if value is the language type of Object. (e.g. arrays, functions, objects, regexes, new Number(0), and new String(''))
Example
_.isObject({});
// => true
_.isObject([1, 2, 3]);
// => true
_.isObject(_.noop);
// => true
_.isObject(null);
// => false

shortcut symbol for converting toString [duplicate]

This question already has answers here:
What's the best way to convert a number to a string in JavaScript?
(25 answers)
Closed 1 year ago.
As you know, if I want to the get numeric value of a variable (e.g. $event) I'd do:
<ax-text-box (valueChange)='documentSearchItem.fromPrice=(+$event)'></ax-text-box>
I add a + to do that.
Is there a simple way like this, to get the string value of a variable ?
p.s. I don't want to use a method. I want to be able to use it in HTML templates.
let v = 2 // whatever value
let s = v.toString()
Lots of ways. A short one without methods is using template strings:
let inputNum = 222;
let newString = `${inputNum}`;
console.log(typeof(newString));

[].slice.call() pattern in javascript [duplicate]

This question already has answers here:
Explanation of [].slice.call in javascript?
(9 answers)
Closed 1 year ago.
Bootstrap 5 Javascript examples sometimes show code like:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'))
Why isn't this just:
var collapseElementList = document.querySelectorAll('.collapse')
What is [].slice.call() doing exactly? I don't understand why you'd slice on an empty array, and then I have no idea what call is doing there. What would be the problem with the obvious way to do this, the second way above?
querySelectorAll returns a NodeList, which is a collection, but not an array.
[].slice.call turns an array-like collection into an array proper. It will allow you to use array methodss on it, eg:
var collapseElementList = [].slice.call(document.querySelectorAll('.collapse'));
const textsOfCollapsedElements = collapseElementList.map(elm => elm.textContent);
Otherwise, if you don't convert it to an array first, you won't be able to use array methods on it.
It's probably most important for forEach. Newer browsers support NodeList.prototype.forEach, but it hasn't been with us that long. In contrast, Array.prototype.forEach has existed forever. So turning the collection into an array allows for forEach to be called on it, even on obsolete browsers that don't support NodeList.prototype.forEach.
It's an idiom for turning anything array-ish (in this case a DOM NodeList) into a real Array by exploiting the fact that Array::slice can work on anything that's iterable and has a .length property.
The modern idiom is Array.from(...).

need reference for documentation on ternary operator using push [duplicate]

This question already has answers here:
When is the comma operator useful?
(15 answers)
Closed 1 year ago.
I have the following:
let currentLocalStorage = [];
currentLocalStorage = (initialLoad) ? JSON.parse(localStorage.getItem('tasks')): (currentLocalStorage.push(taskInput.value),currentLocalStorage)
which works but I would like to get a reference or documentation for the following:
: (currentLocalStorage.push(taskInput.value),currentLocalStorage)
so basically we are pushing on to the array and then defaulting to the array. I was surprised that we can do this and was wondering where one we look for the documentation
This is using the comma operator. Because .push() returns the new length of the array, you want to make sure you don't assign that to currentLocalStorage, so you use the comma operator to have that expression evaluate to currentLocalStorage.
So it effectively becomes currentLocalStorage = currentLocalStorage in that case, except now the array has one more item thanks to .push().

Optimal way of determining array type [duplicate]

This question already has answers here:
JavaScript way to tell if an object is an Array [duplicate]
(6 answers)
Closed 7 years ago.
What is the best way to determining the object type is Array and why?.
var arr = [];
// Method #1
Array.isArray(arr);
// Method #2
toString.call(arr) == "[object Array]"
// Method #3
arr.constructor == Array
All three methods can be used to test if variable is of Array type. However, there are some nuances. I will start from the last to first.
Method #3. Will not work if variable in question came from other winndow/frame. In this case, constructor will point the the different Array object and this check will return false. For the same reason, arr instanceof Array is not bullet-proof. So it's not 100% reliable.
Method #2. This is the method that has been traditionally used to verify array type. In fact, Array.isArray polyfill is based on this method. The only disadvantage is that it's cumbersome and verbose.
Method #1. Is the one from ES5 that should finally be used to test array type, no matter what realm array comes from (like iframe). This is is the best in the list.
The prefered method is to use Array.isArray. This is present in the ES5 language specification and quite well supported by the browsers.
If you plan to support old browsers, You can find a polyfill on MDN. The polyfill is basically your second option.
The last option will not work if you play with iframes.
var arr = myIframe.contentWindow.myArray;
console.log(obj.constructor === Array); //false
The reason is that the Array constructor is diffferent for each window object. Using this to detect arrays will work 99% of the time but will suddenly fail one day.

Categories