Assigning data from an array, or what? - javascript

I came across this line and I'm unsure how it does what it does. The data portion is a json object and later on, the "myarray" variable is used to assign new variables to an array.
The "myItems" object is used to iterate through a .map function over the objects in the data object. But I have no idea how this all gets assigned through the code below:
var myItems = data || [], myarray;

It declares two global variables myItems and myarray. My items is assigned data if data is not undefined, if data is undefined it assigns an empty array to myItems.
The || operator can be used during assignment due to the truthy or falsey nature of variables in Javascript.
Several values equate to false in Javascript such as an empty string "" or undefined. Others such as a String literal != "" (Example "Test") and objects will equate to true. When used in assignment the section of code proceeding the || will not be evaluated if the first expression equates to true.
This link gives a better description of truthy and falsey.

Another way to write this would be:
var myItems;
if (data) {
myItems = data;
} else {
myItems = [];
}
var myarray;

This line of code does the following:
it declares myarray and myItems variables.
data || [] means take data if evaluates to true (not empty), otherwise take new empty array. This is kind of javascript mnemonic to provide fallback/default values.
Assigns the result of previous step to myItems
So, it's better written as
var myarray;
var myItems = data || [];

Here, you're defining two variables called data and myarray (take note of the comma).
The || (logical OR operator) is being lightly abused here. The statement
var myItems = data || [];
Will assign the value of data to myItems if data is not falsy. If it is falsy, however, myItems will be initialised as an empty array with []. Due to lazy evaluation, if data != false, the rest of the statement is not executed.

Related

What’s the difference between “{}” and “[]” while declaring a JavaScript array?

What’s the difference between “{}” and “[]” while declaring a JavaScript array?
Normally I declare like
var a=[];
What is the meaning of declaring the array as var a={}
Nobody seems to be explaining the difference between an array and an object.
[] is declaring an array.
{} is declaring an object.
An array has all the features of an object with additional features (you can think of an array like a sub-class of an object) where additional methods and capabilities are added in the Array sub-class. In fact, typeof [] === "object" to further show you that an array is an object.
The additional features consist of a magic .length property that keeps track of the number of items in the array and a whole slew of methods for operating on the array such as .push(), .pop(), .slice(), .splice(), etc... You can see a list of array methods here.
An object gives you the ability to associate a property name with a value as in:
var x = {};
x.foo = 3;
x["whatever"] = 10;
console.log(x.foo); // shows 3
console.log(x.whatever); // shows 10
Object properties can be accessed either via the x.foo syntax or via the array-like syntax x["foo"]. The advantage of the latter syntax is that you can use a variable as the property name like x[myvar] and using the latter syntax, you can use property names that contain characters that Javascript won't allow in the x.foo syntax.
A property name can be any string value.
An array is an object so it has all the same capabilities of an object plus a bunch of additional features for managing an ordered, sequential list of numbered indexes starting from 0 and going up to some length. Arrays are typically used for an ordered list of items that are accessed by numerical index. And, because the array is ordered, there are lots of useful features to manage the order of the list .sort() or to add or remove things from the list.
When you declare
var a=[];
you are declaring a empty array.
But when you are declaring
var a={};
you are declaring a Object .
Although Array is also Object in Javascript but it is numeric key paired values.
Which have all the functionality of object but Added some few method of Array like Push,Splice,Length and so on.
So if you want Some values where you need to use numeric keys use Array.
else use object.
you can Create object like:
var a={name:"abc",age:"14"};
And can access values like
console.log(a.name);
var a = [];
it is use for brackets for an array of simple values.
eg.
var name=["a","b","c"]
var a={}
is use for value arrays and objects/properties also.
eg.
var programmer = { 'name':'special', 'url':'www.google.com'}
It can be understood like this:
var a= []; //creates a new empty array
var a= {}; //creates a new empty object
You can also understand that
var a = {}; is equivalent to var a= new Object();
Note:
You can use Arrays when you are bothered about the order of elements(of same type) in your collection else you can use objects. In objects the order is not guaranteed.
they are two different things..
[] is declaring an Array:
given, a list of elements held by numeric index.
{} is declaring a new object:
given, an object with fields with Names and type+value,
some like to think of it as "Associative Array".
but are not arrays, in their representation.
You can read more # This Article
Syntax of JSON
object = {} | { members }
members = pair | pair, members
pair = string : value
array = [] | [ elements ]
elements = value | value elements
value =
string|number|object|array|true|false|null
In JavaScript Arrays and Objects are actually very similar, although on the outside they can look a bit different.
For an array:
var array = [];
array[0] = "hello";
array[1] = 5498;
array[536] = new Date();
As you can see arrays in JavaScript can be sparse (valid indicies don't have to be consecutive) and they can contain any type of variable! That's pretty convenient.
But as we all know JavaScript is strange, so here are some weird bits:
array["0"] === "hello"; // This is true
array["hi"]; // undefined
array["hi"] = "weird"; // works but does not save any data to array
array["hi"]; // still undefined!
This is because everything in JavaScript is an Object (which is why you can also create an array using new Array()). As a result every index in an array is turned into a string and then stored in an object, so an array is just an object that doesn't allow anyone to store anything with a key that isn't a positive integer.
So what are Objects?
Objects in JavaScript are just like arrays but the "index" can be any string.
var object = {};
object[0] = "hello"; // OK
object["hi"] = "not weird"; // OK
You can even opt to not use the square brackets when working with objects!
console.log(object.hi); // Prints 'not weird'
object.hi = "overwriting 'not weird'";
You can go even further and define objects like so:
var newObject = {
a: 2,
};
newObject.a === 2; // true
[ ] - this is used whenever we are declaring an empty array,
{ } - this is used whenever we declare an empty object
typeof([ ]) //object
typeof({ }) //object
but if your run
[ ].constructor.name //Array
so from this, you will understand it is an array here Array is the name of the base class.
The JavaScript Array class is a global object that is used in the construction of arrays which are high-level, list-like objects.

Javascript difference between {} and []

I am working on javascript and I run into this:
if i do
let object = {};
object.length
It will complain that object.length is undefined
But
let object = [];
object.length
works
Any know why?
Thanks
In JavaScript, virtually everything is an object (there are exceptions however, most notably null and undefined) which means that nearly all values have properties and methods.
var str = 'Some String';
str.length // 11
{} is shorthand for creating an empty object. You can consider this as the base for other object types. Object provides the last link in the prototype chain that can be used by all other objects, such as an Array.
[] is shorthand for creating an empty array. While also a data structure similar to an object (in fact Object as mentioned previously is in its prototype chain), it is a special form of an object that stores sequences of values.
typeof [] // "object"
When an array is created it automatically has a special property added to it that will reflect the number of elements stored: length. This value is automatically updated by certain methods while also used by others.
var arr = [];
arr.hasOwnProperty('length'); // true
arr.length; // 0
In fact there is nothing special about properties on arrays (although there are few if any good reasons to use them) aside from the engine using them for those methods.
var arr = [];
arr.foo = 'hello';
arr // []
arr.foo // "hello"
arr.length // 0
This is not true of an Object though. It does not have a length property added to it as it does not expect a sequence of values. This is why when you try to access length the value returned is undefined which is the same for any unknown property.
var obj = {};
obj.hasOwnProperty('length'); // false
obj.length; // undefined
obj.foo; // undefined
So, basically an array is a special data structure that expects a sequence of data. Because of this a property is added automatically that represents the length of the data structure.
BONUS: You can use length to trim an array:
var a = [1,2,3,4,5];
a.length; // 5
a.length = 2;
a; // [1, 2]
a.length; // 2
This is because [] is an array object and the length is 0 because there are no elements. {} is an object and there is no property length. The array object does have a property called length, thats why you see the number of elements when you call [].length
[] signifies an array in javascript, so it has length. {} is just declaring an object.
They're different things. One is an object, another is an array.
{} is an object, which has keys and values.
You can't necessarily determine the length of an object since its key-value pairs may not necessarily be numbers or indexed in any way.
[] is an array, which has numbered indices. It's pretty straightforward it has a length.

JavaScript object detection

I am currently practicing javascript and I'm currently having trouble with object detection. I want to create an object and detect whether it exists. Below is some example code I am currently using.
The code sample below is how I am creating my object.
var obj = obj || {};
Should I be using this?
if (typeof obj !== "undefined") {
// code
}
Or this?
if (obj !== null) {
}
The value undefined means that the variable has not been assigned a value. The value null indicates that it has been assigned the value null. The === operator (and its negation, !==) prevent type coercion.
Which is right? It all depends on what you are trying to accomplish. Both undefined and null are "falsy" values, meaning that each one evaluates to false in a boolean context (as do false, 0, and the empty string).
Note that if obj is null, then typeof obj is not "undefined".
The usual practice is to use:
var obj = obj || {};
When that code runs, you can be certain that obj has been defined (because of the var declaration), though it may not have been assigned a value.
If the value of obj resolves to a "falsey" value, then you will assign a reference to a new object.
Possible outcomes are:
If obj has not been assigned a value, a new object reference is assigned.
If obj has previously been assigned a "falsey" value, it will be replaced by a new object reference (which may mess with whatever code assigned it the falsey value).
If obj has previously been assigned a "truethy" primitive value, the following assignments of properties to obj will throw an error and script execution will stop.
if obj is already a reference to an object other than null, then subsequent assignments of properties will be to that object. Depending on the type of object, things may be ok. Or not. Presumably something outside your control created the object and so may modify or destroy it without your knowledge. What will you do?
It is not possible in javascript to deal, in general, with cases 2 and 3, or 4 where it's not your obj you're dealiing with. So use a name that is unlikely to clash with any other and hope you get #1 or #4 and things go well.
Incidentally, code added after yours may still result (more or less) in #4, even if you had #1 at the point the code is executed.
There is no additional benefit to tests like:
if (typeof obj == 'undefined')
because the outcome is essentially the same.

What this JavaScript code doing?

I have this code in JavaScript:
var JSON;
JSON||(JSON={});
Can you tell what this code is doing?
var JSON is declaring a global (or other scope) variable.
JSON||(JSON={}); is first checking to see if JSON evaluates to true or false, and if false, then JSON is set to an empty object;
It is pretty pointless in that context,
var JSON;
creates a variable named JSON
The second part,
JSON||(JSON={});
is equivalent to
if(!JSON){
JSON = {};
}
This can all be skipped and written as
var JSON = {};
It scopes a variable called JSON, then uses the shortcircuit nature of the || operator to assign an empty object to said variable unless that variable has a truthy value.
Its just making JSON an empty object.
This code is doing the following:
Declare variable JSON (JSON === undefined)
Assign an empty object ({}) to JSON if JSON is a falsey value.
Falsey values include: null, undefined, "" (empty string), 0, NaN, false.
JSON has been declared via var JSON, so is set to undefined, meaning that the right hand-side of the operation JSON||... will be executed. In other words, all the code is achieving is:
var JSON = {};
I think this says : if the var 'JSON' is null create a blank javascript obect.

JavaScript Object instantiation

Sometimes I'll see code like this:
var Obj = Obj || {};
What does this do? I have had success writing
array = array || [];
To instantiate an array if it hasn't already been instantiated, however I would like to know a bit more about the mechanics of this.
The technique tries to make use of something called short circuit evaluation... but it's tricky in Javascript, and turns out to be quite dangerous if you try to make use of it for Object instantiation.
The theory behind short circuit evaluation is that an OR statement is only evaluated up to the first true value. So the second half of an OR statement is not evaluated if the first half is true. This applies to Javascript......
But, the peculiarities of Javascript, in particular how undeclared variables are handled, make this a technique that has to be used with great care to instantiate objects.
The following code creates an empty object except if Obj was previously declared in the same scope:
var Obj = Obj || {}; // Obj will now be {}, unless Obj was previously defined
// in this scope function.... that's not very useful...
This is because after var Obj, Obj will be undefined unless it was declared in the same scope (including being declared as a parameter to the function, if any).... so {} will be evaluated. (Link to an explanation of var provided in the comments by T.J. Crowder).
The following code creates an empty object only if Obj has been previously declared and is now falsy:
Obj = Obj || {}; // Better make sure Obj has been previously declared.
If the above line is used when Obj has not been previously declared, there will be a runtime error, and the script will stop!
For example this Javascript will not evaluate at all:
(function() {
Obj = Obj || "no Obj"; // error since Obj is undeclared JS cannot read from
alert(Obj);​ // an undeclared variable. (declared variables CAN
})(); // be undefined.... for example "var Obj;" creates
// a declared but undefined variable. JS CAN try
// and read a declared but undefined variable)
jsFiddle example
But this Javascript will always set Obj to "no Obj"!
var Obj ="I'm here!";
(function() {
var Obj = Obj || "no Obj"; // Obj becomes undefined after "var Obj"...
alert(Obj); // Output: "no Obj"
})();​
jsFiddle example
So using this type of short circuit evaluation in Javascript is dangerous, since you can usually only use it in the form
Obj = Obj || {};
Which will fail precisely when you would most want it to work... in the case where Obj is undeclared.
Note: I mention this in the comments of the penultimate example, but it's important to understand the 2 reasons that a variable can be undefined in Javascript.
A variable can be undefined because it was never declared.
A variable can be undefined because it was declared but has not had a value assigned to it.
A variable can be declared using the var keyword. Assigning a value to an undeclared variable creates the variable.
Trying to use an undefined variable that is also undeclared causes a runtime error. Using an undefined variable that has been declared is perfectly legal. This difference is what makes using Obj = Obj || {}; so tricky, since there is no meaningful form of the previous statement if Obj is either undeclared OR it is a previously existing variable.
The mechanics are a bit unusual: Unlike most languages, JavaScript's || operator does not return true or false. Instead, it returns the first "truthy" value or the right-hand value. So for instance:
alert("a" || "b"); // alerts "a", because non-blank strings are "truthy"
alert(undefined || "b") // alerts "b", because undefined is falsey
alert(undefined || false || 0); // alerts "0", because while all are falsy, 0 is rightmost
More in this blog post.
As Darin said, your var Obj = Obj || {}; is probably not a literal quote, more likely something like this:
function foo(param) {
param = param || {};
}
...which means, "if the caller didn't give me something truthy for param, use an object."
var Obj = Obj || {};
I think that the var here is not necessary. It should be:
Obj = Obj || {};
Where Obj is defined elsewhere. This will simply assign Obj to an empty object if it is null or leave as is of not. You might also leave the var keyword in which case it will ensure that the object is declared even if it wasn't before this statement.
Same for the array: if it is null it will assign it to an empty array.
The key to understanding this syntax is that the result of a boolean or (or and) expression in JavaScript is the last-evaluated component. As has been pointed out by other commenters, JavaScript's shortcircuiting is being used along with this feature to conditionally set the value of array or Obj.
Obj = Obj || {};
This means Obj is set to the value of the expression Obj || {}. If Obj is "true", meaning it evaluates to true (for an object, this means it exists), the result of the expression is Obj, because the expression short-circuits. However, if Obj is "false" (non-existent), the second part of the expression must be evaluated. Therefore, in that case, the value of the expression is {}.

Categories

Resources