Javascript variable declaration : what is "var myVariable = {}"? - javascript

I'm pretty new to plain old JavaScript and to JavaScript frameworks (such as Backbone.js, RequireJS, ...). As I was reading and trying to understand some JavaScript files that I got from a project at work (based on JQuery, Backbone and Require), I've encountered some variable declarations such as:
var myVariable = {}, itemList;
Could someone explain to me what the "{}" is?
PS: might be a silly question but it's definitely not that easy Googling for "{}" as keyword...
Thanks in advance.

{} is just the javascript way of defining a collection or object.
In this example, it is filled with an object literal
var apple = {
type: "macintosh",
color: "red",
getInfo: function () {
return this.color + ' ' + this.type + ' apple';
}
}
var featurelessApple = {};

It's an empty Javascript object literal (A shorthand way of creating an object)
var myVariable = {};
is similar to
var myVariable = new Object();
Both expressions will create an empty object.

myVariable is an object literal, or generic object.
For future reference you can easily see this by using the console in your browser. In Chrome
var myVariable = {}
console.log(myVariable);
This will then print out the entire object. In this
Object {}

That's an empty object literal.
Object literals consist in zero or more key/value pairs enclosed in curly braces. In your example, there are zero key/value pairs, so the object does not define any property.

Related

JavaScript Conceptual Issue with a code. Please give an explanation for the output i am getting

I am having difficulty in understanding the following code, i have put a comment where i do not understand the concept, what exactly is going on
var ob = {};
var ob2 = ['name'];
for(var op of ob2)
{
ob[op]='at'; // here i dont understand what is happening, why here is an array type brackets
}
console.log(ob);
OUTPUT IS
name:'at'
That is just the syntax for accessing or assigning properties of an object dynamically in javascript.
You can think of it as though you are doing: ob.name = 'at'.
There are two ways to access object properties in JavaScript
var person = {
name: 'Jane'
}
person.name
// or
person['name']
// both return jane
in your case, that iterates through members of the array called ob2
first and only element of that array is a string name and it's given to that object as a prop, which becomes like following
ob['name'] = 'at';
// or
ob.name = 'at';
When to use brackets([]) over dot(.)
If you don't know the prop name at runtime you need to go with brackets, if you do know it you can choose either dot notation or brackets
Basically, it's accessing a property of the object ob. In this case, is accessing and creating new properties.
The loop is getting each index value, and for each assign/create a new property using that index value.
That approach is a dynamically way of creating property-names in an object.
ob['name'] = 'at';
ob.name = 'at'; // Just to illustrate
Read a little the docs here -> JavaScript object basics - Learn web development | MDN

The difference between object and plain object in JavaScript?

Couldn’t understand the difference between object and plain object in JavaScript.
I know how Object looks like but don’t understand plain object. I googled about this but couldn’t understand.
As per my understanding normal object looks like below
const object = {};
Or we do call functions as objects in JavaScript
function test() {
}
But what is plain object? how it differs with normal object. Thank you
Edit:
My confusion started about plain object after looking at below error. So my query is to understand the concept of plain object in JavaScript
Actions must be plain objects. Use custom middleware for async actions.
I think you wanted to mean Plain Old JavaScript Object as plain object.
In vanilla JavaScript a POJO (Plain Old JavaScript Object) is the simplest kind of object you could possibly have: a set of key-value pairs, created by the {} object literal notation or constructed with new Object().
Plain Old JavaScript Object:
Using the bracket's syntactic sugar also known as object literal:
var obj = {};
Using the Object() constructor:
var obj = new Object();
Other Than Plain Object:
Using a function constructor:
var Obj = function(name) {
this.name = name;
}
var c = new Obj("hello");
Using ES6 class syntax:
class myObject {
constructor(name) {
this.name = name;
}
}
var e = new myObject("hello");
Plain object(POJO - Plain Old Javascript Object)
var plainObj1 = {}; // typeof plainObj1 --> Object
var plainObj2 = {name : "myName"}; // typeof plainObj2 --> Object
var plainObj3 = new Object(); // typeof plainObj3 --> Object
Non Plain object
var Person = function(){}; //class
var nonPlainObj = new Person(); // typeof nonPlainObj --> function
An Object created by literal notation or new Object are know as plain object. example :
let a = {aaa : 1}
let b = new Object()
while Object created using function are not plain object
let C = function(){}
let d = new C()
You are talking about object literals, which is a literal object, {}. Like array literals use [] instead of new Array(). This is an object whose prototype is Object. A string is an Object too, but its prototype chain looks like: String -> Object. Arrays are Array -> Object. These are all objects.
An object literal's prototype is just, well, Object.
Any object created with object literals notation is called plain Objects in JavaScript
function Animal(){
//Some codes
}
var obj = new Animal();
In your question, you cite that you think both an object literal and a function are both "objects". In JS, function is a type, and so is object. So your original question, those two items are not objects ...
plain objects (sets of key/value pairs wrapped in { } ) are great for storing simple data sets.
var lunch={
sandwich:'furkey',
drink:'soda',
chips:true
}
like in react redux actions are written in key/value pairs.
hope you understand it.

JavaScript: How to create an object having its string name [duplicate]

This question already has answers here:
Accessing nested JavaScript objects and arrays by string path
(44 answers)
Closed 6 years ago.
I have a namespace and class declared in the client. In fact, I have a whole bunch of classes declared in several namespaces. I just need to get an instance of one of them when I get a string from the server on page load that contains the "dotted" namespace.class names.
Currently I use eval to do that but this causes a memory leak, so I'm trying to find an alternative way of instantiating a declared object by knowing only its name. Things like var obj = "myNamespace.myObjectName"(); won't work, obviously.
If I have an object name as a string variable I can use the eval() function to create an instance of that object:
window["myNamespace"] = {};
myNamespace.myObjectName = function() { /* blah */ };
var name = "myNamespace.myObjectName";
var obj = eval("new " + name + "()");
But for several reasons I don't want/cannot to use the eval. How can I create an object by its name without using the eval?
It sounds like you don't control the content of the name variable, so you're stuck with the . being part of the string.
Therefore, you can .split() the string into its name parts, and use .reduce() to traverse from the base object.
window["myNamespace"] = {};
myNamespace.myObjectName = function() {
this.foo = "bar"
};
var name = "myNamespace.myObjectName";
var obj = newObjectFromStringPath(name);
document.querySelector("pre").textContent = JSON.stringify(obj, null, 4);
function newObjectFromStringPath(path, base) {
return new (name.split(".").reduce(function(obj, name) {
return obj != null ? obj[name] : null
}, base || window))
}
<pre></pre>
The newObjectFromStringPath is coded to specifically target a function and call it as a constructor. You can easily make this work to fetch any value by simply removing the new in that function.

Meaning of '{ }' in javascript

What does assigning a variable to {}, mean? Is that initializing it to a function? I have code in a javascript file that says this
GLGE.Wavefront = function(uid) {
GLGE.Assets.registerAsset(this,uid);
this.multimaterials = [];
this.materials = {}; // <---
this.instances = [];
this.renderCaches = [];
this.queue = [];
};
how is that assignment different from an array? Is it a type of array?
What does assigning a variable to {}, mean?
It is an object literal (with no properties of its own).
Is that initializing it to a function?
No, that would be = function () { }.
how is that assignment different from an array?
An array has a bunch of features not found in a basic object, such as .length and a bundle of methods.
Objects are often used to store arbitrary key/value pairs. Arrays are for ordered values.
This is javascript object notation. Particularly {} means empty object, the same as new Object();. See json.org.
That would be an empty JavaScript object.
Using {} creates an object. You can use the object like a hash-map or similar to how you can use arrays in PHP.
var obj = {};
obj['test'] = 'valuehere';
obj.secondWay = 'secondValue';
and you could access them by calling obj.test and obj['secondWay'].
It's an initialized empty object, eg. an object of no particular type. It serves to provide a definition for this.materials so that the code won't have to check it for null or being defined later.
It does create an empty object.
var myObj = {};
Within an object you can define key/value pairs, e.g.:
myObj.color = 'red';
A value can be a function, too:
myObj.getColor = function() { return this.color };
It's JON (Javascript Object Notation) for creating a new empty object. Almost equal in idea to how you'd normally do Object x = new Object() in java, minus the initialization part...

In JavaScript terms how do you name this kind of object?

In JS terminology how do you name this kind of object:
var a = {"a":"wohoo", 2:"hello2", "d":"hello"};
I believe it is not an array as 'length' property is undefined on it.
Then what is it?
thanks
It's just a normal object.
The initializer is called an object literal.
It's just an object, i.e. an instance of Object. Same as doing:
var a = new Object();
a.a = "wohoo";
a["2"] = "hello2";
a.d = "hello";
It is an object.
In Chrome:
>> ({"0": 1}).toString()
"[object Object"]
According to Mozilla, it is an object literal:
An object literal is a list of zero or more pairs of property names and associated values of an object, enclosed in curly braces ({}). You should not use an object literal at the beginning of a statement. This will lead to an error or not behave as you expect, because the { will be interpreted as the beginning of a block.
It is an object (and it work like a hash).
You could go to http://javascript.crockford.com/ for more deep info on javascript.
Its called as a literal notation. Its very powerful stuff dear and has almost replaced old XML in the field. In below example two notations are used both are having same purpose.
var userObject = {
name : 'user1',
age: 24,
run:function(destination){
//make the man run
} };
var userObject = {}; userObject.name =
"user1"; userObject.age = 24;
userObject.run =
function(destination){
//make this man to run };
So now out there its new hot topic whether AJAX (Asynchronous JavaScript & XML) to AJ (Asynchronous JavaScript). Jokes apart its new stuff called as JSON. check below stuff for better understanding this thing.
http://en.wikipedia.org/wiki/JSON
http://msdn.microsoft.com/en-us/library/bb299886.aspx

Categories

Resources