The result returned by Array.isArray is false

As someone diving into the world of javascript and currently unpacking destructuring, I stumbled upon a puzzling snippet that sparked a question in my mind. After some editing, my code was identified as an array by the console, which left me scratching my head.

1: Why is this not recognized as an array?

const heroes = [{
  lol: ['l', 'Iron Man']
}]

const [lol, dc] = heroes;
console.log(Array.isArray(lol)); 

2: On the contrary, why is this one flagged as an array?

const heroes = {
  lol: ['l', 'Iron Man']
}

const {lol, dc} = heroes;
console.log(Array.isArray(lol));

Answer №1

Within the initial code snippet, heroes represents an array where the first element is an object with property lol containing ['l', 'Iron Man'].

{
 lol:['l', 'Iron Man' ]
}

Using destructuring assignment, lol is assigned to this element while dc remains as undefined due to the absence of a second element in the array. As the provided object is not an array, Array.isArray(lol) returns false.

const heroes = [{
 lol:['l', 'Iron Man' ]
}]

const [element1, element2 ] = heroes;
console.log(element1); 

In another scenario, heroes portrays an object. Through the destructuring assignment, lol inherits the value from the lol property within the object (['l', 'Iron Man']). Meanwhile, dc is set based on the dc property, which doesn't exist and consequently defaults to undefined. Since lol is associated with an array, Array.isArray(lol) now evaluates to true.

To capture the array from the initial snippet within lol, additional nesting is required.

const heroes = [{
 lol:['l', 'Iron Man' ]
}]

const [{lol, dc}] = heroes;
console.log(Array.isArray(lol)); 

Answer №2

When extracting data from the 'heroes' variable, there are two different ways to do it. One involves using const [lol, dc] to assign an object with a key 'lol' and value ['l', 'Iron Man'], while the other uses const {lol, dc} to assign an array ['l', 'Iron Man'].

Answer №3

When attempting to destructure in the first example, make sure to use [] for arrays and {} for objects.

In this scenario, start by destructuring the array with [] before moving on to destructure the object within {}.

const heroes = [{
  lol:['l', 'Iron Man' ]
 }]
 
 const [{lol, dr}] = heroes;
 console.log(lol)
 console.log(Array.isArray(lol));

Similar questions

If you have not found the answer to your question or you are interested in this topic, then look at other similar questions below or use the search

Angular updates location, but browser redirects to incorrect page

I want my application to redirect non-logged in users to a login page. Following advice from a popular source, the app listens for routeChangeStart events like this: $rootScope.$on("$routeChangeStart", function(event, next, current) { if ($rootScope.c ...

Seeking assistance with producing results

Is there someone who can provide an answer? What will be the output of the code snippet below when logged to the console and why? (function(){ var a = b = 3; })(); console.log("Is 'a' defined? " + (typeof a !== 'u ...

Display the Meteor Simple Schema for Entities

I've created a Meteor application and set up some database collections with SimpleSchema from https://github.com/aldeed/simple-schema-js. Cards = new Mongo.Collection('cards'); Cards.attachSchema(new SimpleSchema({ title: { type: Str ...

Converting to lower case with Jexl and making replacements in the text

Currently, my code uses the jexl.eval function to evaluate a value like so: jexl.eval("dataset[0].data['Entity Name'].toLowerCase().replace(/ /g, '_')", data); The value of dataset[0].data['Entity Name'] is always a ...

What is the best way to verify the API response in YAML format and ensure that it is neither JSON nor Plain Text using JavaScript?

How can I validate YAML data without validating JSON or plain text? I want to ensure that the response is in YAML format and not in JSON or Plain Text. Is there a method to achieve this without inspecting the content-type header? I attempted to use YAML.l ...

Which specific transitionend (or animationend) event should I use for this application?

I'm feeling a bit lost when it comes to using transitionend (or if I should be using animationend in this scenario). I'm not sure whether to utilize var, node, or box. Essentially, I am a complete beginner in this case. My goal is to have my div ...

Extract values from a JSON array to populate a select list with ID and Value pairs

I appreciate your help. I have now passed in the array as JSON and set the datatype to json, following your example like this: {"car_make_id":"3","car_engine_type":"Non-Turbo Petrol"}{"car_make_id":"3","car_engine_type":"Non-Turbo Diesel"} However, my sc ...

"Effortlessly Engage Users with Rails and AJAX Comment Posting

Running a simple blog app dedicated to video game reviews, I encountered an issue with AJAX. As a self-taught student developer, I'm facing a challenge where posting comments on review pages triggers a full page refresh instead of dynamically updating ...

Reasoning behind splitting this solution into a function utilizing Javascript

Today, while working on a coderbyte problem, I managed to solve it on my own without any outside help, and it felt fantastic. However, upon completion, I realized that I solved it without creating any functions. Rather, I kept referring back to a previous ...

Arranging a Perl array reference by its numerical order

I have extracted XML data and I am passing the values as a reference. The information in the reference is: $VAR1 = [ { 'tender_data' => [ { 'total_mwh' => '191.4600', ...

Extract Key from JSON/Dictionary in Python

I've been struggling to remove certain key-value pairs from my JSON output, but nothing I've tried seems to be effective. The solution involves converting a CSV file to JSON and then deleting the unwanted keys from it. import csv, json import pa ...

Is there a way to show all the items within a specific folder simply by clicking on the folder's name?

When a folder name is clicked, I would like to display all images from that particular folder. Currently, the code displays the list of folder structure and images separately, but my goal is to show the images only when the folder name is clicked. List of ...

Creating a dynamic side navigation menu that adjusts to different screen sizes

I have been working on a project's webpage that was initially created by another Software Engineer. After he left, I continued to work on the webpage. The issue I encountered is that he preferred a side menu over a navbar using the left-panel and righ ...

Collect the text shown in an alert message created with JavaScript

I'm currently unsure if this is achievable or not. In one of my scenarios, I aim to extract text that appears in alert boxes on external websites by including my JavaScript file. Is there a method to obtain the text content shown in an alert message ...

Is there a way to adjust the quantity individually, both increasing and decreasing as needed?

I am currently working on implementing a shopping cart feature using pure JS that allows users to increase and decrease the quantity of items. When the + or - button is clicked, both items in the shopping cart will be affected simultaneously if there are 2 ...

"Failure in bundling with NodeJS using nexe and fusebox

I am attempting to convert a nodejs application into an .exe file. I initially tried using pkg, but encountered errors with half of the node-modules. Now, I am experimenting with a different method. However, when I run the following command: nexe index.js ...

What steps should I take to ensure my API secret remains secure during my next.js deployment?

Recently, I created a small internal application using React and Next.js. To keep my API key and secret secure, I followed the instructions on how to use an .env file provided by Next.js. In my api/hello.js file, I have a simple request that looks like th ...

Adjust text size using the "increase toggle"

I'm having trouble adjusting the font size of my text within the <div class="comment more>. Whenever I try to wrap the text in a <p>, the "more toggle" functionality stops working properly. Instead of revealing more text when I click on "m ...

Populate tabulator table with nested data fetched through an ajax call

I received an API response from a store in JSON format containing three records at the first level. The structure of the response includes data, error_no, msg fields. Within the data field at the second level, I have data.items, data.total_pages, data.to ...

Use xmlhttprequest function during text input instead of traditional form submission

Is it possible to implement a search form xmlhttprequest that dynamically updates results as the user types, rather than requiring them to submit a form? function customersController($scope, $http) { $scope.search = function() { $scope.url = &apos ...