Console setting for displaying hex numbers - javascript

I've just noticed that when logging a data structure which contains a hexadecimal string value to the console, it output's the field as 1, instead of the string value. This is happening in Chrome and Safari.
At the top of the screenshot, you can see an object being logged, this object has an '_id' field, this string is a MongoDb ObjectId, in a nutshell, it's a hexadecimal string.
You can see at the top of the screenshot that the _id field contains a string but when it's (the object) value is being printed (the expanded view), it's being displayed as (Number) 1.
The second log is me console.log'ing the value explicitly, i.e.
//Where obj is the object being logged in the screenshot.
console.log(obj.data._id);
Unsure exactly what's happening here, I can't see how the value being logged would be output as Number 1, that is not the base 10 value of the hexadecimal string, the console is surely making some assumption about the value, and processing it, unsure exactly what's going on there though.
So my question is
Why is 1 being printed here?

Without knowing what else has happened to the object after it's been sent to the console, I'm assuming what you are seeing here is how Chrome's console log keeps a reference to the object, it doesn't hold a snapshot at the time of console logging, but a live reference to the object.
Below is a simple example.
Open up Chromes console,. you will see {x: "one"}, but when you expand the object you will see x: 1 and not x: "one"..
var a = {
x: "one"
};
console.log(a);
a.x = 1;

Related

chrome debugger inconsistency in object data

I don't understand how to interpret this debug data. I do a console.log of my object, and on the summary-line that appears in the console I am shown windows: array[0] but if I expand the object, I am shown that windows is an array of 2 items.
Which is the correct one?
My code seem to run on the summary version, ie. windows array being empty.
Does anyone know what my problem is - why is the object presented in an inconsistent way?
The object is being mutated between when you print it and when you view it. When it's initially logged, it's empty but by the time you open it, 2 items have been added.
var obj = { arr: [] };
console.log(obj); // Will say { arr: Array[0] }
obj.arr.push(1); // Open it up in the console after this
Basically, the dev tools print a string that's representative of it's state at the time of the log but it stores a reference to the object in the console itself.

When does the javascript console evaluate the contents of a printed object?

I have found that when using console.log on a nested object the result seems to print after subsequent operations have performed, but only when logging an object with a depth of at least two.
Consider the following example:
function addNumbers(data) {
data.container.firstNumber++
console.log(data); // 3
data.container.firstNumber++
}
var numberData = {
container : {
"firstNumber": 1
}
};
console.log(numberData); // 3
addNumbers(numberData);
I assumed that with this example I would see numberData printed with the values 1 and then 2. In actuality, the value is 3, 3. My first thought was perhaps there is some race condition here where the values changes before the log operation can complete, but if you add more specific references to the object, you will get the value that matches the console.log's position in the code like this:
function addNumbers(data) {
data.container.firstNumber++
console.log(data.container); // 2
data.container.firstNumber++
}
var numberData = {
container : {
"firstNumber": 1
}
};
console.log(numberData.container); // 1
addNumbers(numberData);
Why doesn't the variable evaluate to its value relative to the position of the console.log in the first example, but does in the second example?
relevant fiddle
Most browsers only fetch the properties of an object logged to the console when you expand the object -- and often note this in a tooltip next to the object reference.
They also tend to only expand the object the first time and cache from then on, so the console is not a reliable way to inspect objects.
To get around this, browsers offer a watch panel that will update more frequently and can be used with breakpoints or stepping to get the current state of an object repeatedly.

Unable to check object values in javascript json prepared from json encoded php array

Server side code
$NATIVE_TEST_TEMPLATE_IDS = array(145);
Client side code to assign PHP array into javascript -
var nativetestTemplates = "<?php echo json_encode($NATIVE_TEST_TEMPLATE_IDS); ?>"; //PHP array into JSON.
But now, the JSON object nativetestTemplates that I have here does not look ready for doing Object instance checks. I need to check if, say, 145 exists in the object nativetestTemplates.
Following are details of console log -
nativetestTemplates.length -> 5
Also, the individual elements of the array have the following -
nativetestTemplates[0] -> [
nativetestTemplates[1] -> 1
nativetestTemplates[2] -> 4
nativetestTemplates[3] -> 5
nativetestTemplates[4] -> ]
So, what did I do wrong and what is the best method to check if an element exists in the object.
Update
After fixing mistake pointed out by Djave, I am still having problem checking if an element exists in the object nativetestTemplates.
Here is my code -
Case 1
var testAdnetworkId = $("#adnetwork_type").val(); //reading selected dropdown value
console.log("see "+$.inArray(testAdnetworkId, nativetestTemplates)+" and "+nativetestTemplates[testAdnetworkId]);
This returns following even when testAdnetworkId has a matching value -
see -1 and undefined
Case 2
But, if I do this -
var testAdnetworkId = 145; //hardcoded integer val
I get the desired output for $.inArray check -
see 0 and undefined
console.dir of testAdnetworkId in case 1 gives this -
0 "1"
1 "4"
2 "5"
However in case 2, it gives -
0 145
Can, someone please explain the proper way to do object property check in Case 1 (reading value of select dropdown)
Don't wrap it in quotes, you are saying
var nativetestTemplates = "[145]";
you want it to say
var nativetestTemplates = [145];
So, your code would read:
var nativetestTemplates = <?php echo json_encode($NATIVE_TEST_TEMPLATE_IDS); ?>; //PHP array into JSON.
The reason that you are getting the weird output ([, 1, 2 etc) is that Javascript is just finding the character 0, 1, 2 characters from the start of the string, rather than the item at the start of the array.
Edit
Funnily enough its the same issue, you are muddling up your variable types again. Because you are getting the val() of (I imagine) an input field, you are looking for a string again.
console.log(typeof($("#adnetwork_type").val())); // Logs 'string'
Don't fret though, you can fix this.
var testAdnetworkId = parseInt($("#adnetwork_type").val()); //reading selected dropdown value
parseInt() is your friend. It tries its best to replace a string or other variable with a number, which is what you want. You will see here http://codepen.io/EightArmsHQ/pen/Kjgfh that it works.
More on variable types:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Guide/Values,_variables,_and_literals
you need to parse json variable in javascript as following:
nativetestTemplates = JSON.parse(nativetestTemplates);
Now nativetestTemplates.length will give you correct result.

Javascript Associative Array Key Error

I have been having a recurring issue with Javacript associative arrays. Basically, I have a piece of code that looks like:
var l = assoc['2191'];
console.log(l); // >> outputs 'undefined'
console.log(assoc); // >> correctly outputs the associative array
When I print my associative array, it is printed correctly and I can see that '2191' is in fact a key in the array. Even when I go through the javascript console in Chrome, I can type "assoc['2191']" and it correctly returns the associated object. However, whenever I do this in my actual script, it always evaluates to "undefined".
Does anyone know why this has happening? I have checked the type of the key, and "string" is the right choice.

Array containing objects has wrong length

I have an array like:
errors = [ {...}, {...}, {...} ]
It's an instanceof array, yet it only returns 1 for .length?
Relevant code:
if(data.error){
errors.push({'element':ele,error:data.error});
}
//Above is looped a few times and there are N number of errors now inside
console.log(errors) //Returns 2+ objects like {...}, {...}
console.log(errors.length) //Returns 1
For Uzi and Muirbot, here's the errors array:
[
Object
element: b.fn.b.init[1]
error: "You must enter "example" into the field to pass"
__proto__: Object
,
Object
element: b.fn.b.init[1]
error: "Crap!"
__proto__: Object
It is correct, this code:
var errors = new Array();
errors.push({'element':'ele', error:'data.error'});
...adds ONE object to the array. The object has two properties.
It's possible your code is executing in an order other than what you're expecting. ie, when you log both errors and errors.length, errors does contain only 1 object. But after that you are adding to the errors array, and only after that are you looking at the console. At that point you could see a larger array in errors for two reasons - first, your actual code isn't logging errors but some object that contains errors. In that case the console display is live, and will show you not what was in errors at the time, but what is in it now. Alternatively, the console could just be taking some time to log errors.
Without more code I can't be sure if this is the case. But you could verify it by replacing console.log(errors); with console.log(errors[1]);. If errors is really only 1 long at the time, it will log undefined.
The problem was that Chrome's Web Inspector's console.log is an async event. So, the length was a property lookup so it gave that back instantly, but the object with two items inside was held off until the rest of the events had fired.
In the future I, and others with this issue, should use debugger; instead.
is it an Array object or something that resembles it?
arrays do work:
> a = [{a:1}, {b:2}]
[Object, Object]
> a.length
2
you'll have to provide more code.
and now that you've provided the relevant code, the correct answer is what Steve Wellens said (which was downvoted, by the way).
Array.push adds a single element, objects may have more than one key but they're still a single object so your real case was different from your original example, which of course works.
another possibility:
> a = []
[]
> a.length = 2
2
> a
[]
> a.length
2
> a instanceof Array
true

Categories

Resources