What was Douglas Crockford trying to convey with the term 'created in an alternate window or frame'?

What did Douglas Crockford mean when he mentioned that the is_array() test might not correctly identify arrays created in a different window or frame?

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        value.constructor === Array;

How does the following code account for windows and frames when determining if a variable is an array?

var is_array = function (value) {
    return value &&
        typeof value === 'object' &&
        typeof value.length === 'number' &&
        typeof value.splice === 'function' &&
        !(value.propertyIsEnumerable('length'));
};

Answer №1

Consider this scenario: If you have an iframe with its own window, any Array created within that context will not pass a different window's test. This is due to the assumption made by the last condition, which references the current window's Array object, not the one in the iframe.

var isArray = document.querySelector("iframe").contentWindow.Array === Array;
// false (incorrect, it actually is an array)

Check out this jsFiddle.

The alternative approach involves understanding that typeof categorizes an Array as an "object", and examining properties specific to Arrays.

However, this method can be deceived by creating an object that mimics an array.

var isArray = is_array(Object.create({length: 0, splice: function() {}}));
// true (not accurate, it's not truly an array)

Explore this jsFiddle.

Another technique involves utilizing Object's toString() method to retrieve the internal class.

var isArray = ({}).toString.call(value) == "[object Array]";
// true (correctly identifies it as an array)

View this jsFiddle.

This method is effective in a multi-window setup and cannot be easily fooled (though it may involve more processing, it is unlikely to cause performance issues).

Answer №2

In my opinion, Alex's approach outshines Crockford's. This response aims to highlight the flaw in Crockford's methodology.

Consider the following:

I intentionally crafted a defective object.

function Silly(){}
Silly.prototype.length = 0;
Silly.prototype.splice = function () {}

var silly = new Silly();

is_array(silly);
// true

Clearly, if you encounter someone assigning length to the prototype, feel free to express your frustration.

However, this is acceptable:

function Average(){
    Object.defineProperty(this, 'length', {
        get: function () { return 42; }, 
        enumerable: false
    });
}
Average.prototype.splice = function () {}

var a = new Average();

is_array(a);
// true

Therefore, it is best not to attempt to outsmart common practices, as you cannot predict what other developers might do.

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

The property 'body' cannot be read because it is undefined

I have been attempting to incorporate passport logic into my controllers file, but I encountered an issue. When I place the logic inside the controllers, it gives me an error message saying "Cannot read property 'body' of undefined." However, whe ...

A guide on identifying the data type of a value entered into an HTML table using JavaScript

Currently, I am tackling a contenteditable HTML table challenge. My goal is to enforce the insertion of only numeric values while alerting the user if they attempt to input strings or non-numeric characters. Can anyone provide guidance on how to achieve th ...

Not adhering to directive scope when transclusion is used, despite explicit instructions to do so

Trying to use a transcluding directive within another controller, but the inner scope isn't being redefined as expected. Despite trying different methods, I can't seem to figure out what's going wrong. The simplified code looks like this: ...

What is the best way to assign three different dates in my protractor test?

I am facing an issue with setting random dates in 3 date fields in a row using Protractor. The problem is that Protractor sets the dates too quickly and sometimes assigns invalid dates like: first data: 01/08/1990 (correct) second data: 01/09/0009 (inva ...

How can we efficiently load and display all images from a directory using Node.js and JavaScript?

My strategy involves reading all image file names from a specific directory and passing them as an array to the front-end JavaScript. The front-end script then iterates through the array to dynamically create image elements. Step 1: node const path = requ ...

Getting props value in parent component using Vue JS

In my development project, I am working with three key components: component-1, component-2, and an App component. Initially, I pass a Boolean prop from component-1 to component-2. Through the use of a @click event, I am able to toggle this prop value betw ...

Converting a String into an Array using JSON

My dilemma involves converting an Array of Json elements from a String to an Object Array using Gson. Despite researching methods online, none of them seem to properly address my specific scenario. ["2": {"id": 2, "name": "Cannonball", "sp": 5, "overall_a ...

What is the best way to add a simple Search bar to the Material UI Data Grid component?

If we take a look at this data grid example: check it out here I'd like to incorporate a simple search bar similar to the one shown here Can someone provide guidance on how to add this feature to Data Grid MUI? ...

How can server convert the data from Websocket 8.5, which sends `<Buffer>`, into JSON format?

Exploring websocket connections, I am looking to send a JSON object from the client to the server: const WebSocket = require('ws'); const wss = new WebSocket.Server({port: 8082}); wss.on("connection", (ws) => { console.log('s ...

Exploring new options to deduct time from Kendo UI timepickers without relying on Javascript

My current project involves an Asp.net MVC 4 application that includes a Time entry screen. This screen utilizes various Kendo controls and Razor Html helpers to enhance the user experience, such as: @(Html.Kendo().TimePickerFor(m => m.StartTime).Name( ...

Is it possible to assign a class to the initial word within a designated class?

How can I customize the first and second word of a specific class in my code? This is an example of my current code: <h2 class="content-heading">Latest News</h2> I would like to achieve something similar to this: <h2 class="content-headi ...

The qTip comment box vanishes when focused on by IE/Edge browsers using touch devices

A unique JavaScript library called qTip is being utilized in my project. The application includes a StarRating and Comments feature, both of which are enabled by this plugin. After selecting a rating using the stars, users have the option to add comments, ...

Display information in a detailed table row using JSON formatting

I have set up a table where clicking on a button toggles the details of the corresponding row. However, I am having trouble formatting and sizing the JSON data within the table. Is there a way to achieve this? This is how I implemented it: HTML < ...

What is preventing the audio from playing in Safari?

Recently, I developed a small JavaScript program that is meant to play the Happy Birthday tune. This program utilizes setInterval to gradually increase a variable, and depending on its value, plays or pauses certain musical notes. However, I encountered ...

Struggling to display AJAX GET results on my webpage, although they are visible in the Google Element Inspector

I'm working on a basic invoice page where I need to populate a dropdown box from my MySQL database. The issue I'm facing is that when I select an item, the description box doesn't get prepopulated as expected. I've checked in the networ ...

Determine whether there is text present on a webpage using JavaScript

I am familiar with Python coding from selenium import webdriver driver = webdriver.Chrome() driver.get('http://WEBSITE') assert 'TEXT' in driver.page_source However, I now require the equivalent JavaScript code. ...

Detecting the absence of an object

When using my Drag and drop Listview, I am able to collect the dragged and dropped files by calling: var objects=Data.GetData(DataFormats.FileDrop, false); In addition, I can cast this and retrieve paths of all dragged and dropped files: string[] Droppe ...

The console is showing messages before the task is completed

When using console.log to write detailed messages about the current task expected to be performed by Protractor, I noticed that these messages are appearing on the console before the actual task is executed in the browser. An example of this is: it(' ...

Improving efficiency for handling a vast number of inputs in React applications

Dealing specifically with Material UI, I am faced with the challenge of rendering a large number of inputs (more than 100) while effectively managing global state. Performance issues arise when using the Material UI <TextField /> component, with noti ...

Managing toggles for save and edit buttons in Vue - a comprehensive guide

I am currently working on a Vue 'app' within a larger Django application as a means to enhance my understanding of Vue. My objective is to create unique forms that can be edited independently. I have been experimenting with this for some time n ...