What does mean of variable in javaScript? [duplicate] - javascript

This question already has answers here:
What does the following code mean in javascript? [duplicate]
(2 answers)
Closed 6 years ago.
javaScript(variable)
var s = s || {};
s.c = {};
what purposes it will be use?

var s = s || {};
This means that if s is null, undefined or false (it computes to false), then an empty object {} will be assigned to s, so that the second line would not cause an error.
But this notation is inacurate. It should be something like:
var s = (typeof s == 'object') ? s : {};
because in the first example if s is a number the second line will still cause an error.
In the second example notation A ? B : C; is equal to:
if(A){
B;
}else{
C;
}

Related

How do I recognize an empty JSON object in JS returned by my Rails controller? [duplicate]

This question already has answers here:
How do I test for an empty JavaScript object?
(48 answers)
Closed 4 years ago.
How do I check for an empty JSON object in Javascript? I thought the key was
var isEmpty = (response || []).length === 0;
but this isn't it. In my JS console, I have tried
jsonresp = {}
{}
jsonresp.length
undefined
What's driving this is I have a Ruby on Rails controller that is returning the following
render json: job_id.eql?(cur_job_id) ? {} : json_obj
In the case where the controller returns the "{}" is where I'm having trouble on the JS side recognizing if it is empty or not.
You can also try:
if (typeof jsonresp == 'undefined' || typeof jsonresp == 'null'){
// some logic here
}
You can use Object.keys() function to get keys of the object as an array and then check the array to see whether it is empty.
var obj = {};
var arr = Object.keys(obj);
console.log(arr);
console.log("Is Empty : " + (arr.length == 0));
🏄 Shortly:
const isEmpty = !Object.keys(jsonresp).length

concatenating two object keys in JSON [duplicate]

This question already has answers here:
How to use a variable for a key in a JavaScript object literal?
(16 answers)
Closed 5 years ago.
console.log(a) ; // console window result= 1
console.log(b);// console window result= 2
var c = {a : b};// any recommendations here?
var d = JSON.stringify(c);
d = encodeURIComponent(d);
I need final result of d = {1:2};
You can use computed property
var c = {[a] : b};

Is it possible in Javascript to get the name of a variable? [duplicate]

This question already has answers here:
Determine original name of variable after its passed to a function
(9 answers)
JavaScript: Get Argument Value and NAME of Passed Variable [duplicate]
(7 answers)
Closed 7 years ago.
I know this is completely useless, but I'm nonetheless curious. Is it possible to do something like the below?
function getVariableName ( v )
{
// .... do something .....
// return the string "v"
}
var x = 69;
var y = "somestring";
console.log(getVariableName(x)); // prints "x" to the console
console.log(getVariableName(y)); // prints "y" to the console
function getArgNames(fn) {
var matches = fn.toString().match(/\(([a-z_, ]+)\)/i);
if (matches.length > 1) {
return matches[1].replace(/\s+/g, '').split(',');
}
return [];
}
That will return an array of the names of all arguments passed in to the function.

What does '|| {}' means [duplicate]

This question already has answers here:
What does "var FOO = FOO || {}" (assign a variable or an empty object to that variable) mean in Javascript?
(8 answers)
Closed 8 years ago.
I stumbled with the following JavaScript code:
var Employee = function (entity) {
var employee = this;
entity = entity || {};
employee.employeeId = entity.EmployeeId;
employee.email = entity.Email;
employee.firstName = entity.FirstName;
employee.lastName = entity.LastName; // ....
But I couldn't understand the following sentence:
entity = entity || {};
|| is the OR statement in JavaScript. Your function receives entity as variable. When entity is null or undefined, your function will fill it up with empty object which is the same as {}.

Get JSON property from fully qualified string [duplicate]

This question already has answers here:
Convert string in dot notation to get the object reference [duplicate]
(6 answers)
is it evil to use eval to convert a string to a function? [closed]
(4 answers)
Closed 10 years ago.
Say I have a JSON object like this:
var a = {
"b" : {
"c" : 1
}
}
is there a quick way to get at c when I know the string "b.c" ?
I guess I could split the string by dots then drill down into c from that but I was hoping there was a quick way to do this in one go.
like I was hoping maybe var c = a["b.c"] but that doesnt work
How about something like this, as you suggested using a split:
var a = {
"b" : {
"c" : 1
}
}
var n = "b.c".split(".");
var x = a;
for(var i = 0; i < n.length; i++){
x = x[n[i]];
}
//x should now equal a.b.c
Here is a working example
In the event that the path is not valid, there is some extra checking that should be done. As my code stands above, x will be undefined if the final part of the path is invalid (e.g "b.d"). If any other part of the path is invalid (e.g. "d.c") then the javascript will error.
Here is a modified example that will end the loop at the first instance of undefined, this will leave x as undefined and will ensure the javascript can continue to execute (no error!)...
var n = "d.c".split(".");
var x = a;
for (var i = 0; i < n.length; i++) {
x = x[n[i]];
if (typeof(x) == "undefined") {
break;
}
}
Here is an example of this in action
var a = {
"b" : {
"c" : 1
}
}
var c = "b.c".split(".").reduce(function(obj, key) {
return obj[key];
}, a);
alert(c)
See reduce. The link also show a how to implement shim for the browsers that doesn't support ES5. Notice that this code is simplified, assumes the keys are present in the objects.

Categories