Using dot notation with number passed into function - javascript

If I have an object and function
var obj {
"1234": {"example": "sample"},
"5678": {"example": "sample"}
}
function example(num, str) {
if obj[num].hasOwnProperty(str) {
//manipulate property
}
return obj;
}
then later call the function,
obj(1234, "example")
Why do I have to write obj[num] instead of obj.num? Shouldn't dot notation be acceptable because the value being passed will always be an integer and not have quotations around it, i.e. obj.1234 would work but not obj."string"?

Why do I have to write obj[num] instead of obj.num?
Because obj[num] takes the value of num (for instance, 1234) and uses that value as the property name, but obj.num uses "num" (literally) as the property name. Brackets vs. dot is how the JavaScript parser knows when you're giving the property name literally (dot notation) or using an expression you want to use the result of (brackets notation).
(Side note: Granted, when we do foo[1], we literally mean the property 1 in foo. But from the parser's perspective, we're effectively using an expression there.)

Related

Prototype using Square Brackets (Vanilla JS solution only)

How can I apply a prototype to constructor function using (square brackets). I don't want to use dot notation because it does not evaluate the variable but rather returns the variable name and I want the prototype to be more dynamic. Below is what I am trying to achieve but I can't get it to work.
var prototyper = function(constructor_name, prototype_name, data)
{
main[constructor_name][__prototype__][prototype_name] = new Function(data);
}
prototyper("classify","alert_classification","alert(this.classification)");
You want bracket notation for the variable properties (…[constructor_name] and …[prototype_name]) but dot notation for the constant property ….prototype. You will need to mix them into
function prototyper(constructor_name, method_name, fn) {
main[constructor_name].prototype[method_name] = fn;
}
(jsfiddle demo)

Used function argument to access JSON Array javascript

I have a basic function taking an argument. I will use this argument to as index to access the array in JSON file. I want to take advantage of this argument instead of hard-coded inside the function. However, for some reasons, javascript is not return me the right value.
var obj = {
"first":[
["aaaaa"],
["bbbbb"],
["ccccc"],
["ddddd"],
["eeeee"]
]
}
I have a javascript function to access the file.
function addElement(ID) {
console.log(obj.ID);
}
and now if I use
addElement("first"); //this return me undefined.
I do not want to explicitly mention obj.first in order to access the right JSON object. I would like to make it more generic so that the method can be re-used. Am I missing anything here?
Thanks...
JavaScript supports both dot notation and a property name literal (obj.foo), and brackets notation and a property name string (obj["foo"]).* In the latter case, the string can be the result of any expression.
So you'd need brackets notation, not dot notation:
function addElement(ID) {
console.log(obj[ID]);
}
obj.ID accesses the property ID. obj[ID] accesses the property whose name is the string from the variable ID.
* Just for completeness: In ES6, it will support property name Symbols in brackets notation as well, but that's not relevant to your code.

Passing a parameter into a Javascript method

I have the following code:
function isFieldEmpty(input)
{
if(document.frmRegister.input.value == "")
{
return false;
}
return true;
}
I call it using isFieldEmpty("fieldName"). However, I think the "input" bit is incorrect...
Can anyone help?
That code is looking for a property literally called "input" on frmRegister. To look for "fieldName" for example (the value of input), you want bracketed notation:
if(document.frmRegister[input].value == "")
// Change -------------^-----^
In JavaScript, you can access the property of an object using either dot notation and a literal property name (obj.foo) or using bracketed notation and a string property name (obj["foo"]). In the latter case, the property name string can be the result of any expression, including a variable or argument lookup.

How to access attribute of object as a variable?

I have two objects:
object1={
type: 'obj1',
nName: 'nName'
}
object2={
type: 'obj2',
pName: 'pName'
}
In my js code, I have:
object=GET_OBJECT();
The GET_OBJECT() method returns either object1 or object2, then, I would like to access the object's name attribute which is either nName or pName.
I have one method which will get the name (pName or nName) of the returned object:
function getName(Object, name){
return object.name;
}
where I would like the name to be a variable, so that I can access the pName or nName in this way:
object=GET_OBJECT();
var name='';
if(object.type=='obj1')
name='nName';
else
name='pName';
var finalName=getName(object, name);
But seems it won't work since in:
function getName(Object, name){
return object.name;
}
name is a variable. In JS, is there any way to access attribute as a variable?
Try like this:
function getName(Object, name) {
return Object[name];
}
AS many times before I wonder why people provide solutions and not knowledge. Otherwise the asker will repeat the same mistakes over and over.
The original code uses a function to retrieve an attribute. It is assumed that it is possible to use the parameter to invoke the parameter. In more technical words, Dot notation is being used which must be a valid JavaScript identifier. Tha name after the dot is the pointer the content. Therefore getName always is accessing the attribute name which is likely to be undefined.
The solution shown uses Bracket notation in which uses the content of the parameter (which may not exist) as identifier and then, it resolves the content and this is why it actually works.
Dot notation is faster and easier to read and would be adviced if both are valid options. Bracket notation is to be used when you need resolving in run time. That is what happens when you define setters and getters internally. The following code will use the string passed to ensure (using bracket notation) that whenever you use the identifier by dot notation will call the functions passed.
function myClass(){
//setX and getX should be also defined previous to this
this.__defineSetter__("x",this.setX);
this.__defineGetter__("x",this.getX);
//Object.defineProperty can also be used
};
var tObject = new myClass();
tObject.x = 10; //Getter being called

What is the type of "keys" in JavaScript?

I bumbed into one of those moments when I just lose the focus and start wondering on a silly question:
var a = {
b: "value"
}
What is the typeof 'b' and I don't mean the typeof "value", but the actual Key labeled as b?
background:
I started wondering about this when I had to create a key which is a string:
var a = {
"b": "value"
}
because at a later point it is referenced as:
a["b"]
And then ended up wondering about the original question.
In object literal terms, b is a property. Properties are either strings or symbols in JavaScript, although when defining the property name inside an object literal you may omit the string delimiters.
for (key in a) {
alert(typeof key);
//-> "string"
}
Property names are automatically coerced into a string. You can try this yourself by using a numeric literal as a property name.
var object = {
.12e3: 'wut'
};
object[.12e3]; // 'wut'
object['.12e3']; // undefined
object['120']; // 'wut'
// Let’s try another numeric literal:
object = {
12e34: 'heh'
};
object[12e34]; // 'heh'
object['12e34']; // undefined
object[1.2e35]; // 'heh'
object['1.2e35']; // undefined
object[1.2e+35]; // 'heh'
object['1.2e+35']; // 'heh'
For this reason, I’d recommend using only string literals for property names.
From Unquoted property names / object keys in JavaScript, my write-up on the subject:
Quotes can only be omitted if the property name is a numeric literal or a valid identifier name.
[…]
Bracket notation can safely be used for all property names.
[…]
Dot notation can only be used when the property name is a valid identifier name.
I also made a tool that will tell you if any given property name can be used without quotes and/or with dot notation. Try it at mothereff.in/js-properties.
b is a string, it's just a shorthand syntax, so you write
var a = {
b: "value"
}
instead of
var a = {
"b": "value"
}
Keep in mind that JavaScript objects are hash tables and the keys are just strings. You may omit the quotes around property names during declaration, but if you use reserved words for property names or any other name that happens to be an invalid identifier, such as starting with a digit, or containing spaces, you would have to wrap the property names in quotes:
var a = {
"1b": "value",
"b and c": "value",
"+12345": "value"
};
Also note that you can reference the properties of objects using the dot notation or the subscript notation regardless of whether quotes were used when they were declared. However, if you use property names that would be invalid identifiers, such as the ones in the above example, you are forced to use the subscript notation:
a.1b // invalid (dot notation)
a["b and c"]; // valid (subscript notation)
var a = {$ : 'hello', 2123 : 'number'};
for(var key in a) {
console.log(typeof key)
}
Keys in javascript objects can be strings and symbols. symbol is a primitive data type in javascript.

Categories

Resources