New to javascript, need some help with basic questions and getting started

I’m new to javascript, coming from PHP. I have worked with it a bit in the past but want to dive in deeper. I have a few questions.

1
Are associative arrays just constructed like objects or is there a special syntax for them, like in PHP with ‘key’ => ‘value’? I realize arrays are objects in JS (since almost everything is), but I am wondering if there is a special associative array type or if I should really be thinking “objects” not “associative arrays” in JS.

2
How do I iterate over the arrays but save the contents?

    var test_array = [1, 2, 3, 4]

    test_array.forEach(function(key, value) 
    {
    if (key == 1) {
    	var result = key;
    }
    });

console.log(key) // should be 1, instead, I get a reference error, it is undefined.`

3
Can you use .forEach over a normal object? I could not get it to work with objects but only with non-associative arrays.

4
With a for loop, is there any way to get the value of an element in an array or object being iterated over, rather than just the key of the element?

var object_as_array = {day: 'monday', 'month' : 'march', 'season' : { 'summer' : 'hot' } };

    for (index = 0; index < object_as_array.length; ++index) {
    	console.log(object_as_array[index]);
    }

5
How do I copy an entire object as text in (any) browser’s dev tools? (I’ll use whatever it takes.) Right now I can copy the top level, which is usually something like { Object, Object, Object } so not very helpful. I just want to be able to copy and paste the entire contents of the object after I send it to console through console.log(object). Right clicking and copying it only copied the first level. (Preferably only for direct properties of the object, but I will take whatever I can get, including functions and inherited properties if that is the only way.)

6
. In php, we can do:

$colors = ['red', 'blue', 'green'];

$found_red = false;

foreach ($colors as $color) {
	if ($color === 'red') {
	$found_red = true;
}




var_dump($found_red); // true

But I don’t know how to do this basic construction in JS, for either arrays or associative arrays or plain objects (if there is a difference). I think this is some sort of scoping issue.

Any help with any of these would be appreciated.

JavaScript doesn’t have associative arrays - that notation is a way to reference objects - not arrays.

Either update the array in place using forEach or create a new array using map

No - it only works for Array and a few new types recently added.

Don;t use a for loop for objects -use a for…in loop or the new for…of

You can use JSON.serialize() to convert an object to a JSON string and JSON.parse() to change it back.

$colors = ['red', 'blue', 'green'];
$found_red = $colors.some(function(e) {return e === 'red'});
console.log($found_red);
1 Like
  1. Well, objects are similar to associative arrays in that you can access their properties in a similar way (although this is less common), like
var obj = {};

obj.foo = 'bar';    // <- usually, you'll see this variant
obj['foo'] = 'bar'; // <- but this is also possible

The latter variant is useful if the name of the property isn’t fixed, but set during runtime.

However, since ES6 there are also Maps, which may be more useful as mere data collections, and kind of behave like what you might call associative arrays in JS (e.g. you can use forEach() on them directly, as opposed to plain objects – see below).

  1. Any variable declared within (or passed to) the forEach() callback will only accessible within its scope, so you’ll have to declare them outside of it. Also note that you’d need to log result here, as the key variable will be lost anyway. Like
var testArray = [1, 2, 3, 4];
var result;

// Note that the callback's first argument is the value, 
// the second the index
testArray.forEach(function(value, index) {
  if (index === 1) {
    result = index;
  }
});

console.log(result);
  1. No, but you can iterate over its keys, like
var obj = {
  foo: 1,
  bar: 2
};

Object.keys(obj).forEach(function(key) {
  console.log(obj[key]);
});

However, objects are iterable, so you can use the for...in loop on them (or since ES6, the for...of loop).

  1. Plain objects don’t have a length property, but you can use one of the above possibilities to iterate over their properties (or values).

  2. You can use JSON.stringify(), which does exactly that – convert an object to a string. :-) Like

var obj = {
  foo: 1,
  bar: 2
};

// Logs {"foo":1,"bar":2}
console.log(JSON.stringify(obj));
  1. Yes, scoping may be an issue – see my response to 1).

Good luck, and welcome to the JavaScript side! :-)

x-post

1 Like

Thanks to both of you, you’ve cleared up a number of topics for me.

I have been looking at ways to determine the type of javascript things, and it is difficult because of all the edge cases. typeof will tell you something is an object, not an array, even though it looks like there is an array type.

The example code was also helpful.

A few tack on questions.

1
What other types does .forEach work on besides arrays and maps?

2
How can I tell what the scope of things like .forEach is? The for loop, and I think the for … in loop doesn’t have a scope problem from my testing, but .forEach does? I am not sure why. Is it because it accepts a call back instead of simple arguments?

3
Is there any way to access the value of a key in a for … in loop other than using the key itself in the loop to get the key’s associated value?
(In a PHP foreach loop, you can use either that value or key or both, you dont have to use the key to get at the value associated with the key.)

Here is what I have been doing:

var obj = {
  foo: 1,
  bar: 2
};

for (var prop in obj) {
  var value = obj.[prop];
  // also have been doing this, which I guess is the same thing:
  var value = obj.prop;
}

Thanks again.

Anything that is iterable can be converted to an array so forEach can be used on just about anything that has an order to it.

JavaScript usually applies function level scope to everything unless you define them with let or const (both introduced in 2015).The scope of anything defines in the callback function is that function although you can override what this refers to by specifyig it as the second parameter after the callback.

You could use a for…of loop instead (introduced to JavaScript in 2015) - that iterates over the values rather than over the keys.

This topic was automatically closed 91 days after the last reply. New replies are no longer allowed.