Javascript variable declaration syntax - javascript

I'm taking charge of a javascript webapp. It's very complex, and I'm having some trouble with syntax:
getThemeBaseUrl = function() {
var customConfigPath = "./customer-configuration";
if (parseQueryString().CustomConfigPath) {
customConfigPath = parseQueryString().CustomConfigPath;
}
var clientId = parseQueryString().ClientId;
return customConfigPath + "/themes/" + clientId;
};
parseQueryString = function() {
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
while ( m = re.exec(queryString)) {
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
}
return result;
};
in particular parseQueryString().CustomConfigPath and the var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m;
The first seems to be a sort of property access by the parseQueryString function.
The second seems an array declaration, but without the Array() constructor. Also, the m value is recalled without the presumed array result in the while cycle.

By looking at:
parseQueryString().CustomConfigPath
you can say that parseQueryString() is expected to return an object with CustomConfigPath property.
And from this:
var result = {};
you see that result is indeed an object ({} is an empty object literal). It is not an array. Later, in a loop, there is:
result[decodeURIComponent(m[1])] = decodeURIComponent(m[2]);
so we're assigning properties to the result object. One of this properties will be (as we can expect) a CustomConfigPath. This will be taken from the query string - we'll use regular expression to do this: re = /([^&=]+)=([^&]*)/g. So address of the webpage on which this code is executed looks like: http://example.com/something?SomeKey=value&CustomConfigPath=something.
General syntax for assigning properties to an object is:
result[key] = value;
// key -> decodeURIComponent(m[1])
// value -> decodeURIComponent(m[2])

parseQueryString().CustomConfigPath calls the parseQueryString function, which returns an object. Then it accesses the CustomConfigPath property of that object. A common idiom for the first 4 lines of the function is:
var customConfigPath = parseQueryString().CustomConfigPath || "/.customer-configuration";
var result = {}, queryString = location.search.substring(1), re = /([^&=]+)=([^&]*)/g, m is a declaration of 4 different variables, not an array:
result is an empty object
queryString is the query string from the current URL, with the ? removed.
re is a regular expression
m is a variable that isn't initialized, it will be assigned later in the while loop.

Related

Javascript: How to create an object from a dot separated string?

I ran into this potential scenario that I posed to a few of my employees as a test question. I can think of a couple ways to solve this problem, but neither of them are very pretty. I was wondering what solutions might be best for this as well as any optimization tips. Here's the question:
Given some arbitrary string "mystr" in dot notation (e.g. mystr = "node1.node2.node3.node4") at any length, write a function called "expand" that will create each of these items as a new node layer in a js object. For the example above, it should output the following, given that my object name is "blah":
blah: { node1: { node2: { node3: { node4: {}}}}}
From the function call:
mystr = "node1.node2.node3.node4";
blah = {};
expand(blah,mystr);
Alternately, if easier, the function could be created to set a variable as a returned value:
mystr = "node1.node2.node3.node4";
blah = expand(mystr);
Extra credit: have an optional function parameter that will set the value of the last node. So, if I called my function "expand" and called it like so: expand(blah, mystr, "value"), the output should give the same as before but with node4 = "value" instead of {}.
In ES6 you can do it like this:
const expand = (str, defaultVal = {}) => {
return str.split('.').reduceRight((acc, currentVal) => {
return {
[currentVal]: acc
}
}, defaultVal)
}
const blah = expand('a.b.c.d', 'last value')
console.log(blah)
Here's a method that popped up in my mind. It splits the string on the dot notation, and then loops through the nodes to create objects inside of objects, using a 'shifting reference' (not sure if that's the right term though).
The object output within the function contains the full object being built throughout the function, but ref keeps a reference that shifts to deeper and deeper within output, as new sub-objects are created in the for-loop.
Finally, the last value is applied to the last given name.
function expand(str, value)
{
var items = mystr.split(".") // split on dot notation
var output = {} // prepare an empty object, to fill later
var ref = output // keep a reference of the new object
// loop through all nodes, except the last one
for(var i = 0; i < items.length - 1; i ++)
{
ref[items[i]] = {} // create a new element inside the reference
ref = ref[items[i]] // shift the reference to the newly created object
}
ref[items[items.length - 1]] = value // apply the final value
return output // return the full object
}
The object is then returned, so this notation can be used:
mystr = "node1.node2.node3.node4";
blah = expand(mystr, "lastvalue");
var obj = {a:{b:{c:"a"}}};
const path = "a.b.c".split(".");
while(path.length > 1){
obj = obj[path.shift()];
}
obj[path.shift()] = "a";

Setting array key value pair JavaScript

So, I am having an issue and for the life of me I cannot seem to resolve it. It seems very basic, but I just cannot understand for the life of me why this code is not working.
My issue is, I am assigning a key value pair to an array, but the values DO NOT get assigned. Is it a variable scope issue?
Here is my code
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Trim your key because cookie strings look like this:
"__utma=250730393.1032915092.1427933260.1430325220.1430325220.1; __utmc=250730393; __utmz=250730393.1430325220.1.1.utmcsr=(direct)|utmccn=(direct)|utmcmd=(none); clicks=22; _gat=1; _ga=GA1.2.1032915092.1427933260"
so when you split on ; there will be an extra space before some of the key names.
function getcookie(cookiename){
var mycookies = []; // The cookie jar
var temp = document.cookie.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0].trim(); // added trim here
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
Demo: JSBin
mycookies should be populated assuming temp.length is greater than 0. Your return value is always going to be undefined; mycookies[cookiename] is never assigned a value.
Try adding console.log(mycookies) just before your return statement.
Mycookies should be an Object, not an Array.
var mycookies = {};
JavaScript arrays are not associative arrays, only possible index values are numerical, starting with 0 and ending at array.length - 1. What you might have seen in examples before or used in another language before was JavaScript object, which does, in fact, behave as an associative array. You can access object values by object['key'] or as object.key. The first is used only when accessing key using a variable or a key which includes illegal characters, i.e. some-key, otherwise it's recommended to use dot access, as illustrated in second example.
Therefore your mycookies variable should be an object, not an array.
If you change your line var mycookies = []; to var mycookies = {};, i.e. change it from empty array to empty object, the remaining code should work as you expected.
Here is an example snippet for fixed code, I added a mock cookies string so it can work reliably:
var mockCookies = "a=1;b=2;c=3";
function getcookie(cookiename){
var mycookies = {}; // The cookie jar
var temp = mockCookies.split(";");
var key = "";
var val = "";
for(i=0;i<temp.length;i++){
key = temp[i].split("=")[0];
val = temp[i].split("=")[1];
mycookies[key] = val;
}
return mycookies[cookiename];
}
function printCookie(name) {
alert(getcookie(name));
}
<button onclick="printCookie('a')">Get a</button>
<button onclick="printCookie('b')">Get b</button>
<button onclick="printCookie('c')">Get c</button>
My friend, you are a little confused (maybe you have programmed in PHP) because in JavaScript, an Array is not a associative key : value object, it is an indexes based object. But what you looking for is an Object Literal
function getcookie (cookiename){
var i, max, keyvalue, key, val,
cookiesObj = {}, //empty object literal
cookiesArr = document.cookie.split(";");
for(i=0, max=cookiesArr.length; i<max; i+=1) {
keyvalue = cookiesArr[i].split("=");
key = keyvalue[0].trim();
val = keyvalue[1].trim();
cookiesObj[key] = val;
}
return cookiesObj[cookiename];
}
But you can refactor your code:
function getcookie (cookiename) {
var cookie = "",
cookies = document.cookie.split(";");
cookies.forEach(function (item) {
var keyvalue = item.split("="),
key = keyvalue[0].trim(),
val = keyvalue[1].trim();
if (key === cookiename) {
cookie = val;
return false; //exit from iteration
}
});
return cookie;
}

quick question about JavaScript variables

Not sure what to search for here, so apologies if I'm repeating another question.
I'm wondering if there are any issues that I'm not aware of with using the following syntax in JavaScript:
var a = {};
var b = a.niceCoat = {};
Seems handy, but I just want to make sure...
That is perfectly fine, because a was declared previously. The expressions will be evaluated as
var a = {};
var b = (a.niceCoat = {});
I.e. it first assigns a new empty object to a.niceCoat and the result (the result of an assignment is the assigned value) to b.
But be aware of something like
var a = b = 'c';
which, again, is evaluated as
var a = (b = 'c');
Only a will be in local scope, b would be global. If you want b to be local too, you have to declare it beforehand: var b;. Something like var a = var b = .... does not work (not valid syntax).
Slightly off topic:
This method is indeed handy. Imaging you have an object of objects, something like:
var map = {
foo: {},
bar: {}
};
and you want to get the object for a certain key or create a new one if the key does not exists. Normally one would probably do:
var obj = map[key];
if(!obj) { // works because if the key is set, it is an object
obj = {}; // which evals to true
map[key] = obj;
}
// now work with obj
With the above method, this can be shortened to
var obj = map[key];
if(!obj) {
map[key] = obj = {};
}
And we can make it even shorter with the logical OR operator (||):
var obj = map[key] || (map[key] = {});
(though it might be less readable).
You can do that. a.niceCoat = {} will be evaluated first, which assigns the object to the property and also has the object as result, which you then can assign to the variable.
You should however be aware that b and a.niceCoat are now referencing the same object, so if you put anything in the object it will show up for both the variable and the property:
var a = {};
var b = a.niceCoat = {};
b.x = 42;
alert(a.niceCoat.x); // shows 42
There no issue with that. It's the same as:
var b = (a.niceCoat = {});
Which is the same as:
a.niceCoat = {};
var b = a.niceCoat; // Now b and a.niceCoat are the same object
Just be careful with declaring entirely new variables with it like:
var i = j = 0;
Which is the same as:
j = 0;
var i = j;
Notice how j is not declared with the var keyword.
this is how you create an empty object in javascript. nothing wrong with it.
Yep, absolutely valid.
E.g.
var a = {};
var b = a.niceCoat = {};
a.foo = function() { alert('foo!'); };
a.foo(); // shows the alert

Using a variable as identifier in a json array

I'm wondering if it is possible to use assigned variables as identifier in a json array. When I tried this, I was getting some unexpected results:
(Code is simplified, parameters are passed in a different way)
var parameter = 'animal';
var value = 'pony';
Util.urlAppendParameters(url, {
parameter: value
});
Util.urlAppendParameters = function(url, parameters) {
for (var x in parameters) {
alert(x);
}
}
Now the alert popup says: 'parameter' instead of 'animal'. I know I could use a different method (creating an array and assigning every parameter on a new line), but I want to keep my code compact.
So my question is: Is it possible to use a variable as an identifier in the json array, and if so, could you please tell me how?
Thanks in advance!
You will need to build your object in two steps, and use the [] property accessor:
var parameter = 'animal';
var value = 'pony';
var obj = {};
obj[parameter] = value;
Util.urlAppendParameters (url, obj);
I don't think JSON Array is the more correct term, I would call it Object literal.
No, you can't use a variable as an identifier within an object literal like that. The parser is expecting a name there so you can't do much else but provide a string. Similarly you couldn't do something like this:
var parameter = 'animal';
var parameter = 'value'; //<- Parser expects a name, nothing more, so original parameter will not be used as name
The only work around if you really really want to use an object literal on a single line is to use eval:
Util.urlAppendParameters (url, eval("({" + parameter + " : value})");
Depending on your needs you could also build your object with a helper function;
Util.createParameters = function(args) {
var O = {};
for (var i = 0; i < arguments.length; i += 2)
O[arguments[i]] = arguments[i + 1];
return O
}
Util.urlAppendParameters (url, Util.createParameters(parameter, value, "p2", "v2"));

Best javascript syntactic sugar

Here are some gems:
Literals:
var obj = {}; // Object literal, equivalent to var obj = new Object();
var arr = []; // Array literal, equivalent to var arr = new Array();
var regex = /something/; // Regular expression literal, equivalent to var regex = new RegExp('something');
Defaults:
arg = arg || 'default'; // if arg evaluates to false, use 'default', which is the same as:
arg = !!arg ? arg : 'default';
Of course we know anonymous functions, but being able to treat them as literals and execute them on the spot (as a closure) is great:
(function() { ... })(); // Creates an anonymous function and executes it
Question: What other great syntactic sugar is available in javascript?
Getting the current datetime as milliseconds:
Date.now()
For example, to time the execution of a section of code:
var start = Date.now();
// some code
alert((Date.now() - start) + " ms elapsed");
Object membership test:
var props = { a: 1, b: 2 };
("a" in props) // true
("b" in props) // true
("c" in props) // false
In Mozilla (and reportedly IE7) you can create an XML constant using:
var xml = <elem></elem>;
You can substitute variables as well:
var elem = "html";
var text = "Some text";
var xml = <{elem}>{text}</{elem}>;
Using anonymous functions and a closure to create a private variable (information hiding) and the associated get/set methods:
var getter, setter;
(function()
{
var _privateVar=123;
getter = function() { return _privateVar; };
setter = function(v) { _privateVar = v; };
})()
Being able to extend native JavaScript types via prototypal inheritance.
String.prototype.isNullOrEmpty = function(input) {
return input === null || input.length === 0;
}
Use === to compare value and type:
var i = 0;
var s = "0";
if (i == s) // true
if (i === s) // false
Multi-line strings:
var str = "This is \
all one \
string.";
Since you cannot indent the subsequent lines without also adding the whitespace into the string, people generally prefer to concatenate with the plus operator. But this does provide a nice here document capability.
Resize the Length of an Array
length property is a not read only.
You can use it to increase or decrease the size of an array.
var myArray = [1,2,3];
myArray.length // 3 elements.
myArray.length = 2; //Deletes the last element.
myArray.length = 20 // Adds 18 elements to the array; the elements have the empty value. A sparse array.
Repeating a string such as "-" a specific number of times by leveraging the join method on an empty array:
var s = new Array(repeat+1).join("-");
Results in "---" when repeat == 3.
Like the default operator, || is the guard operator, &&.
answer = obj && obj.property
as opposed to
if (obj) {
answer = obj.property;
}
else {
answer = null;
}
var tags = {
name: "Jack",
location: "USA"
};
"Name: {name}<br>From {location}".replace(/\{(.*?)\}/gim, function(all, match){
return tags[match];
});
callback for string replace is just useful.
Getters and setters:
function Foo(bar)
{
this._bar = bar;
}
Foo.prototype =
{
get bar()
{
return this._bar;
},
set bar(bar)
{
this._bar = bar.toUpperCase();
}
};
Gives us:
>>> var myFoo = new Foo("bar");
>>> myFoo.bar
"BAR"
>>> myFoo.bar = "Baz";
>>> myFoo.bar
"BAZ"
This isn't a javascript exclusive, but saves like three lines of code:
check ? value1 : value2
A little bit more on levik's example:
var foo = (condition) ? value1 : value2;
The Array#forEach on Javascript 1.6
myArray.forEach(function(element) { alert(element); });
Following obj || {default:true} syntax :
calling your function with this : hello(neededOne && neededTwo && needThree) if one parameter is undefined or false then it will call hello(false), sometimes usefull
In parsing situations with a fixed set of component parts:
var str = "John Doe";
You can assign the results directly into variables, using the "destructuring assignment" synatx:
var [fname, lname] = str.split(" ");
alert(lname + ", " + fname);
Which is a bit more readable than:
var a = str.split(" ");
alert(a[1] + ", " + a[0]);
Alternately:
var [str, fname, lname] = str.match(/(.*) (.*)/);
Note that this is a Javascript 1.7 feature. So that's Mozilla 2.0+ and Chrome 6+ browsers, at this time.
Immediately Invoked Arrow function:
var test = "hello, world!";
(() => test)(); //returns "hello, world!";
I forgot:
(function() { ... }).someMethod(); // Functions as objects
Create an anonymous object literal with simply: ({})
Example: need to know if objects have the valueOf method:
var hasValueOf = !!({}).valueOf
Bonus syntactic sugar: the double-not '!!' for converting pretty much anything into a Boolean very succinctly.
I love being able to eval() a json string and get back a fully populated data structure.
I Hate having to write everything at least twice (once for IE, again for Mozilla).
Assigining the frequently used keywords (or any methods) to the simple variables like ths
var $$ = document.getElementById;
$$('samText');
JavaScript's Date class providing a semi-"Fluent Interface". This makes up for not being able to extract the date portion from a Date class directly:
var today = new Date((new Date()).setHours(0, 0, 0, 0));
It's not a fully Fluent Interface because the following will only give us a numerical value which is not actually a Date object:
var today = new Date().setHours(0, 0, 0, 0);
Default fallback:
var foo = {}; // empty object literal
alert(foo.bar) // will alert "undefined"
alert(foo.bar || "bar"); // will alert the fallback ("bar")
A practical example:
// will result in a type error
if (foo.bar.length === 0)
// with a default fallback you are always sure that the length
// property will be available.
if ((foo.bar || "").length === 0)
Here's one I just discovered: null check before calling function:
a = b && b.length;
This is a shorter equivalent to:
a = b ? b.length : null;
The best part is that you can check a property chain:
a = b && b.c && b.c.length;
I love how simple it is to work with lists:
var numberName = ["zero", "one", "two", "three", "four"][number];
And hashes:
var numberValue = {"zero":0, "one":1, "two":2, "three":3, "four":4}[numberName];
In most other languages this would be quite heavy code. Value defaults are also lovely. For example error code reporting:
var errorDesc = {301: "Moved Permanently",
404: "Resource not found",
503: "Server down"
}[errorNo] || "An unknown error has occurred";
int to string cast
var i = 12;
var s = i+"";
element.innerHTML = ""; // Replaces body of HTML element with an empty string.
A shortcut to delete all child nodes of element.
Convert string to integer defaulting to 0 if imposible,
0 | "3" //result = 3
0 | "some string" -> //result = 0
0 | "0" -> 0 //result = 0
Can be useful in some cases, mostly when 0 is considered as bad result
Template literals
var a = 10;
var b = 20;
var text = `${a} + ${b} = ${a+b}`;
then the text variable will be like below!
10 + 20 = 30

Categories

Resources