0

What is the difference between an array and an object in JavaScript?

22nd Jun 2018, 1:40 PM
Eli Ben Shimon
Eli Ben Shimon - avatar
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!
22nd Jun 2018, 2:18 PM
Redek Project
Redek Project - avatar
+ 1
thank you Redek Project
22nd Jun 2018, 2:36 PM
Eli Ben Shimon
Eli Ben Shimon - avatar
+ 1
Redek Project, foo and bar are strings, right?
22nd Jun 2018, 2:37 PM
Eli Ben Shimon
Eli Ben Shimon - avatar
+ 1
and console.log(); can also be document.write(); ?
22nd Jun 2018, 2:38 PM
Eli Ben Shimon
Eli Ben Shimon - avatar
+ 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).
22nd Jun 2018, 2:45 PM
Redek Project
Redek Project - avatar
+ 1
Redek Project ok! thank you!!
22nd Jun 2018, 3:01 PM
Eli Ben Shimon
Eli Ben Shimon - avatar