0
What is the difference between an array and an object in JavaScript?
6 Answers
+ 4
Hello Savant,
Without going into too much detail, the difference between `object` and `array` is the structure and prototypes they contain.
The structure of the two elements is different:
For `arrays`, you will use"[ ]" to define that it is an array. In this table you will put your value directly and you will be able to access it via the index of your values. For example :
let myArray = ["foo", "bar", 0, 25, "apple"];
console.log(myArray[0]); // => foo
console.log(myArray[2]); // => 0
console.log(myArray.length); // => 5
myArray.push("Savant"); // Add new element on my array
console.log(myArray); // => ["foo", "bar", 0, 25, "apple", "Savant"]
For `object` you will use the "{ }" to define that it is an object. For this object, you will give a name to your value and you will access it by calling it. For example :
let myObject = { name: "Savant", learning: "JS", level: 7 };
console.log(myObject.name); // => Savant
console.log(myObject.level); // => 7
myObject.foo= "bar"; // Add new element on my object
console.log(myObject); // => { name: "Savant", learning: "JS", level: 7, foo: "bar" };
Hope this helped!
+ 1
thank you Redek Project
+ 1
Redek Project, foo and bar are strings, right?
+ 1
and console.log(); can also be document.write(); ?
+ 1
~ Redek Project, foo and bar are strings, right?
> Indeed, in `myArray`, foo and bar are strings
~ and console.log(); can also be document.write(); ?
> Not quite, we will use `console.log()` when we want to display something in the javascript console (F12 on browser) while we will use `document.write()` to display something in our visual window (HTML).
+ 1
Redek Project ok! thank you!!