Different ways of defining unassign variable in javascript [duplicate] - javascript

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 6 years ago.
I know when we want to define unassign variable in Javascript we can do:
var p;
and the other:
var p ={};
i want to know differences between these two ways, and if i define a variable in second way it is not null! what is the value in the variable, if we want using it in a if condition, for example :
var p ={};
if(p=='what i shout put there')
{}

var p is creating an unassigned variable. So console.log(p) will log undefined
var p ={}; is a way of creating object using literal notation.
Object p have methods like constructor,hasOwnProperty,toLocaleString etc
if(p=='what i shout put there'){}
If it is required to check if p is an object then below snippet is useful
if(Object.prototype.toString.call( a ) === '[object Object]'){
// Do rest of code
}
An object can have properties. like
var p={};
p.a ="someValue";
In this case you can check by
if(p.a === 'someValue'){
// Do rest of code
}

var p = {};
It is not unassigned ,it is infact assigned to the empty object
If you do below , it will be trut
if(p) {} // truthy

Related

Why do I need to bind a shadowed function that is called through the same object? [duplicate]

This question already has answers here:
How does the "this" keyword in Javascript act within an object literal? [duplicate]
(4 answers)
Closed 4 years ago.
Was doing some dirty things to Array.prototype when I ran into this:
Array.prototype.hook_pop = function(callback) {
var base_pop = this.pop.bind(this); //<-- this works
var base_pop = this.pop; //<-- this doesn't work
this.pop = function() {
var ret = base_pop();
callback(ret, this);
return ret;
}
}
Initially I tried using the non-working option and got an error "Uncaught TypeError: Cannot convert undefined or null to object".
The way I've understood it, unless otherwise bound, "this" should point to the object through which the method is called from, in this case the array instance. When called on the same object though, either way, "this" should be the same when being passed to the pop function, whether its bound or not. Why doesn't the second option work?
var ret = base_pop();
In this line you're invoking base_pop() by itself, and not as a method of any object. Because of this, its this value isn't set.

Access Object AND property of object using variables in Javascript [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 7 years ago.
I am aware you can access properties of objects in javascript using variables like this Object['property'] but I want to access the Object using a variable too.
// The object and his function
var Foo = {};
Foo.bar = function() { console.log("I am a useful function dood"); }
// The accessors
var obj = 'Foo';
var method = 'bar';
But when I try it in the way I think is right, I get the following. As all links in the world seem to be about accessing object properties with variables I don't seem to be able to sift one out that accesses objects like this too.
typeof obj // "object"
typeof Foo[method] // "function"
typeof [obj].foo // undefined
typeof [obj][method] // undefined <-- This is what I'm trying to use
Am I able to access the object like this?
EDIT
According to answers, if the object is globally scoped I could use window[obj][method] but the above is contained in an immediately invoked function like this:
(function(){
// The stuff from above...
})();
Will this work I will have to put this into an identifiable var that is globally scoped?
PS I will never ever use eval();
If your Foo object is at the global object then :
window[obj][method]() //I am a useful function dood`
Else , you will need to supply more info.

Using String to get JSON Property [duplicate]

This question already has an answer here:
Accessing a JSON property (String) using a variable
(1 answer)
Closed 8 years ago.
I want to use a string as a JSON property in JavaScript.
var knights = {
'phrases': 'Ni!'
};
var x = 'phrases';
console.log(knights.x); // Doesn't log "Ni!"
When I run this code, it obviously doesn't work because it interprets "x" and not the contents of the variable "x".
The full code in context on pastebin: http://pastebin.com/bMQJ9EDf
Is there an easy solution to this?
knights.x looks for a property named x. You want knights[x], which is equivalent to knights['phrases'] == knights.phrases.
Full code (fixing a couple of typos in your example):
var knights = {
"phrases": "Ni!"
};
var x = 'phrases';
console.log(knights[x]); // logs Ni!
Try this to access using variables having string values
kinghts[x]
Basically this is trick
kinghts[x]==knighted["phrases"]==knighted.phrases.
knights.x will get a key named x, So it'll return undefined here.
knights.x is the same as knights['x'] - retrieving a property under the key x. It's not accessing the variable x and substituting in the value. Instead, you want knights[x] which is the equivalent of knights['phrases']

Convert String name into javascript variable name? [duplicate]

This question already has answers here:
"Variable" variables in JavaScript
(9 answers)
Closed 8 years ago.
Problem with example:
Variable name: var product5519 = 10;
I can get this name in the form of a String i.e
var str = "product5519"
Is there any way to convert it into variable name so that i can use the value assigned to
product5519
I know one way to solve this problem i.e using eval(str)
If there is any another way to solve it please tell?
Once you are certain creating a global variable was the Right Thing to do, you can add your variable to the window object, like so:
window[str] = 42;
This works because variable lookups end up trying the window object if the variable was not defined in an inner scope.
It's a bit hacky but if you wanted to make a global variable you could do:
var str = "product5519";
window[str] = value;
You could then access the variable like:
window[str];
window.str;
str; // Assuming that there is no local variable already named "str"
you could do something like:
window['product5519'] = 'value'
it may be better to have an array of products, depending on the situation ofc.
You can use an associative array:
var variables = [];
variables['product5519'] = 10;
console.log(variables['product5519']);

Use a variable inside a dictionary (associative array) in javascript [duplicate]

This question already has answers here:
Is it possible to define a dynamically named property using object literal in JavaScript? [duplicate]
(7 answers)
Closed 8 years ago.
I have this particular script which uses a javascript dictonary
var z= 'Bingo';
var fruit={ 'Bingo' :1};
var fruit2={ z :1};
alert(fruit[z]);
alert(fruit2[z]);
alert(fruit2['z']);
The first alert gives the expected value 1. However, the second alert gives the alert value as "undefined" and third alert gives the output as 1. Is there a way to use a variable inside a dictionary, ie. can we specify the javascript interpreter to read z as a variable rather than as string 'z'?
Thanks!
Yes, you can do this easily, but not inside an object literal. Property names in object literals are taken literally. They are not variable names. JavaScript quotes them implicitly if you don't quote them.
For example, these two object literals are the same:
{ a: 1 }
{ 'a': 1 }
To use a variable, you need to use [] notation outside an object literal:
var z = 'Bingo';
var fruit2 = {};
fruit2[z] = 1;

Categories