Best javascript syntactic sugar - javascript

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

Related

Is it possible to get the object name passed into a function as a variable from within the function [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Create a input function for several cases [duplicate]

I am trying to return two values in JavaScript. Is this possible?
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
No, but you could return an array containing your values:
function getValues() {
return [getFirstValue(), getSecondValue()]
}
Then you can access them like so:
const [first, second] = getValues()
This is called destructuring assignment and is supported by every major JS environment. It's equivalent to the following:
const values = getValues()
const first = values[0]
const second = values[1]
You can also return an object if you want to assign a name to each value:
function getValues() {
return {
first: getFirstValue(),
second: getSecondValue(),
}
}
And to access them:
const {first, second} = getValues()
Which is the same as:
const values = getValues()
const first = values.first
const second = values.second
It is highly recommended to return an object instead of an array unless the values make sense as a simple tuple, e.g. a coordinate pair [x, y]. With an array, it's easy to forget which value is which, it's harder to add more values later, and it's marginally more difficult to correctly type with TypeScript or JSDoc.
You can do this from ECMAScript 6 onwards using arrays and "destructuring assignments". Note that these are not available in older Javascript versions (meaning — neither with ECMAScript 3rd nor 5th editions).
It allows you to assign to 1+ variables simultaneously:
var [x, y] = [1, 2];
x; // 1
y; // 2
// or
[x, y] = (function(){ return [3, 4]; })();
x; // 3
y; // 4
You can also use object destructuring combined with property value shorthand to name the return values in an object and pick out the ones you want:
let {baz, foo} = (function(){ return {foo: 3, bar: 500, baz: 40} })();
baz; // 40
foo; // 3
And by the way, don't be fooled by the fact that ECMAScript allows you to return 1, 2, .... What really happens there is not what might seem. An expression in return statement — 1, 2, 3 — is nothing but a comma operator applied to numeric literals (1 , 2, and 3) sequentially, which eventually evaluates to the value of its last expression — 3. That's why return 1, 2, 3 is functionally identical to nothing more but return 3.
return 1, 2, 3;
// becomes
return 2, 3;
// becomes
return 3;
Just return an object literal
function newCodes(){
var dCodes = fg.codecsCodes.rs; // Linked ICDs
var dCodes2 = fg.codecsCodes2.rs; //Linked CPTs
return {
dCodes: dCodes,
dCodes2: dCodes2
};
}
var result = newCodes();
alert(result.dCodes);
alert(result.dCodes2);
Since ES6 you can do this
let newCodes = function() {
const dCodes = fg.codecsCodes.rs
const dCodes2 = fg.codecsCodes2.rs
return {dCodes, dCodes2}
};
let {dCodes, dCodes2} = newCodes()
Return expression {dCodes, dCodes2} is property value shorthand and is equivalent to this {dCodes: dCodes, dCodes2: dCodes2}.
This assignment on last line is called object destructing assignment. It extracts property value of an object and assigns it to variable of same name. If you'd like to assign return values to variables of different name you could do it like this let {dCodes: x, dCodes2: y} = newCodes()
Ecmascript 6 includes "destructuring assignments" (as kangax mentioned) so in all browsers (not just Firefox) you'll be able to capture an array of values without having to make a named array or object for the sole purpose of capturing them.
//so to capture from this function
function myfunction()
{
var n=0;var s=1;var w=2;var e=3;
return [n,s,w,e];
}
//instead of having to make a named array or object like this
var IexistJusttoCapture = new Array();
IexistJusttoCapture = myfunction();
north=IexistJusttoCapture[0];
south=IexistJusttoCapture[1];
west=IexistJusttoCapture[2];
east=IexistJusttoCapture[3];
//you'll be able to just do this
[north, south, west, east] = myfunction();
You can try it out in Firefox already!
Another worth to mention newly introduced (ES6) syntax is use of object creation shorthand in addition to destructing assignment.
function fun1() {
var x = 'a';
var y = 'b';
return { x, y, z: 'c' };
// literally means { x: x, y: y, z: 'c' };
}
var { z, x, y } = fun1(); // order or full presence is not really important
// literally means var r = fun1(), x = r.x, y = r.y, z = r.z;
console.log(x, y, z);
This syntax can be polyfilled with babel or other js polyfiller for older browsers but fortunately now works natively with the recent versions of Chrome and Firefox.
But as making a new object, memory allocation (and eventual gc load) are involved here, don't expect much performance from it. JavaScript is not best language for developing highly optimal things anyways but if that is needed, you can consider putting your result on surrounding object or such techniques which are usually common performance tricks between JavaScript, Java and other languages.
function a(){
var d = 2;
var c = 3;
var f = 4;
return {d: d, c: c, f: f};
}
Then use
const {d, c, f} = a();
In new version:
function a(){
var d = 2;
var c = 3;
var f = 4;
return {d, c, f}
}
A very common way to return multiple values in javascript is using an object literals, so something like:
const myFunction = () => {
const firstName = "Alireza",
familyName = "Dezfoolian",
age = 35;
return { firstName, familyName, age};
}
and get the values like this:
myFunction().firstName; //Alireza
myFunction().familyName; //Dezfoolian
myFunction().age; //age
or even a shorter way:
const {firstName, familyName, age} = myFunction();
and get them individually like:
firstName; //Alireza
familyName; //Dezfoolian
age; //35
Other than returning an array or an object as others have recommended, you can also use a collector function (similar to the one found in The Little Schemer):
function a(collector){
collector(12,13);
}
var x,y;
a(function(a,b){
x=a;
y=b;
});
I made a jsperf test to see which one of the three methods is faster. Array is fastest and collector is slowest.
http://jsperf.com/returning-multiple-values-2
In JS, we can easily return a tuple with an array or object, but do not forget! => JS is a callback oriented language, and there is a little secret here for "returning multiple values" that nobody has yet mentioned, try this:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return dCodes, dCodes2;
};
becomes
var newCodes = function(fg, cb) {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
cb(null, dCodes, dCodes2);
};
:)
bam! This is simply another way of solving your problem.
You can also do:
function a(){
var d=2;
var c=3;
var f=4;
return {d:d,c:c,f:f}
}
const {d,c,f} = a()
Adding the missing important parts to make this question a complete resource, as this comes up in search results.
Object Destructuring
In object destructuring, you don't necessarily need to use the same key value as your variable name, you can assign a different variable name by defining it as below:
const newCodes = () => {
let dCodes = fg.codecsCodes.rs;
let dCodes2 = fg.codecsCodes2.rs;
return { dCodes, dCodes2 };
};
//destructuring
let { dCodes: code1, dCodes2: code2 } = newCodes();
//now it can be accessed by code1 & code2
console.log(code1, code2);
Array Destructuring
In array destructuring, you can skip the values you don't need.
const newCodes = () => {
//...
return [ dCodes, dCodes2, dCodes3 ];
};
let [ code1, code2 ] = newCodes(); //first two items
let [ code1, ,code3 ] = newCodes(); //skip middle item, get first & last
let [ ,, code3 ] = newCodes(); //skip first two items, get last
let [ code1, ...rest ] = newCodes(); //first item, and others as an array
It's worth noticing that ...rest should always be at the end as it doesn't make any sense to destruct anything after everything else is aggregated to rest.
I hope this will add some value to this question :)
You can use "Object"
function newCodes(){
var obj= new Object();
obj.dCodes = fg.codecsCodes.rs;
obj.dCodes2 = fg.codecsCodes2.rs;
return obj;
}
All's correct. return logically processes from left to right and returns the last value.
function foo(){
return 1,2,3;
}
>> foo()
>> 3
I would suggest to use the latest destructuring assignment (But make sure it's supported in your environment)
var newCodes = function () {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return {firstCodes: dCodes, secondCodes: dCodes2};
};
var {firstCodes, secondCodes} = newCodes()
I know of two ways to do this:
1. Return as Array
2. Return as Object
Here's an example I found:
<script>
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var arr = [dividend, divisor, quotient];
return arr;
}
// Store returned value in a variable
var all = divideNumbers(10, 2);
// Displaying individual values
alert(all[0]); // 0utputs: 10
alert(all[1]); // 0utputs: 2
alert(all[2]); // 0utputs: 5
</script>
<script>
// Defining function
function divideNumbers(dividend, divisor){
var quotient = dividend / divisor;
var obj = {
dividend: dividend,
divisor: divisor,
quotient: quotient
};
return obj;
}
// Store returned value in a variable
var all = divideNumbers(10, 2);
// Displaying individual values
alert(all.dividend); // 0utputs: 10
alert(all.divisor); // 0utputs: 2
alert(all.quotient); // 0utputs: 5
</script>
Few Days ago i had the similar requirement of getting multiple return values from a function that i created.
From many return values , i needed it to return only specific value for a given condition and then other return value corresponding to other condition.
Here is the Example of how i did that :
Function:
function myTodayDate(){
var today = new Date();
var day = ["Sunday","Monday","Tuesday","Wednesday","Thursday","Friday","Saturday"];
var month = ["January","February","March","April","May","June","July","August","September","October","November","December"];
var myTodayObj =
{
myDate : today.getDate(),
myDay : day[today.getDay()],
myMonth : month[today.getMonth()],
year : today.getFullYear()
}
return myTodayObj;
}
Getting Required return value from object returned by function :
var todayDate = myTodayDate().myDate;
var todayDay = myTodayDate().myDay;
var todayMonth = myTodayDate().myMonth;
var todayYear = myTodayDate().year;
The whole point of answering this question is to share this approach of getting Date in good format. Hope it helped you :)
I am nothing adding new here but another alternate way.
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
let [...val] = [dCodes,dCodes2];
return [...val];
};
Well we can not exactly do what your trying. But something likely to below can be done.
function multiReturnValues(){
return {x:10,y:20};
}
Then when calling the method
const {x,y} = multiReturnValues();
console.log(x) ---> 10
console.log(y) ---> 20
It is possible to return a string with many values and variables using the template literals `${}`
like:
var newCodes = function() {
var dCodes = fg.codecsCodes.rs;
var dCodes2 = fg.codecsCodes2.rs;
return `${dCodes}, ${dCodes2}`;
};
It's short and simple.

How to print the variable name it self in javascript console [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Get name of object In String Javascript [duplicate]

Is there a way to get a variable name as a string in Javascript? (like NSStringFromSelector in Cocoa)
I would like to do like this:
var myFirstName = 'John';
alert(variablesName(myFirstName) + ":" + myFirstName);
--> myFirstName:John
UPDATE
I'm trying to connect a browser and another program using JavaScript. I would like to send instance names from a browser to another program for callback method:
FooClass = function(){};
FooClass.someMethod = function(json) {
// Do something
}
instanceA = new FooClass();
instanceB = new FooClass();
doSomethingInAnotherProcess(instanceB); // result will be substituted by using instanceB.someMethod();
...
From another program:
evaluateJavascriptInBrowser("(instanceName).someMethod("resultA");");
In PHP:
How to get a variable name as a string in PHP?
Like Seth's answer, but uses Object.keys() instead:
const varToString = varObj => Object.keys(varObj)[0]
const someVar = 42
const displayName = varToString({ someVar })
console.log(displayName)
You can use the following solution to solve your problem:
const myFirstName = 'John'
Object.keys({myFirstName})[0]
// returns "myFirstName"
Typically, you would use a hash table for a situation where you want to map a name to some value, and be able to retrieve both.
var obj = { myFirstName: 'John' };
obj.foo = 'Another name';
for(key in obj)
console.log(key + ': ' + obj[key]);
In ES6, you could write something like:
let myVar = 'something';
let nameObject = {myVar};
let getVarNameFromObject = (nameObject) => {
for(let varName in nameObject) {
return varName;
}
}
let varName = getVarNameFromObject(nameObject);
console.log(varName);
Not really the best looking thing, but it gets the job done.
This leverages ES6's object destructuring.
More info here: https://hacks.mozilla.org/2015/05/es6-in-depth-destructuring/
Get a string from any valid Javascript (variable, class):
const nameOf = (f) => (f).toString().replace(/[ |\(\)=>]/g,'');
Examples:
nameOf(() => myVariable) // myVariable
nameOf(() => myVariable.name) // myVariable.name
nameOf(() => myVariable.name.length) // myVariable.name.length
nameOf(() => myVariable.name[10]) // myVariable.name[10]
nameOf(() => MySuperClass) // MySuperClass
Probably pop would be better than indexing with [0], for safety (variable might be null).
const myFirstName = 'John'
const variableName = Object.keys({myFirstName}).pop();
console.log(`Variable ${variableName} with value '${myFirstName}'`);
// returns "Variable myFirstName with value 'John'"
var x = 2;
for(o in window){
if(window[o] === x){
alert(o);
}
}
However, I think you should do like "karim79"
This works for basic expressions
const nameof = exp => exp.toString().match(/[.](\w+)/)[1];
Example
nameof(() => options.displaySize);
Snippet:
var nameof = function (exp) { return exp.toString().match(/[.](\w+)/)[1]; };
var myFirstName = 'Chuck';
var varname = nameof(function () { return window.myFirstName; });
console.log(varname);
var somefancyvariable = "fancy";
Object.keys({somefancyvariable})[0];
This isn't able to be made into a function as it returns the name of the function's variable.
// THIS DOESN'T WORK
function getVarName(v) {
return Object.keys({v})[0];
}
// Returns "v"
Edit: Thanks to #Madeo for pointing out how to make this into a function.
function debugVar(varObj) {
var varName = Object.keys(varObj)[0];
console.log("Var \"" + varName + "\" has a value of \"" + varObj[varName] + "\"");
}
You will need call the function with a single element array containing the variable. debugVar({somefancyvariable});
Edit: Object.keys can be referenced as just keys in every browser I tested it in but according to the comments it doesn't work everywhere.
Shortest way I have found so far to get the variables name as a string:
const name = obj => Object.keys(obj)[0];
const whatsMyName = "Snoop Doggy Dogg";
console.log( "Variable name is: " + name({ whatsMyName }) );
//result: Variable name is: whatsMyName
Since ECMAScript 5.1 you can use Object.keys to get the names of all properties from an object.
Here is an example:
// Get John’s properties (firstName, lastName)
var john = {firstName: 'John', lastName: 'Doe'};
var properties = Object.keys(john);
// Show John’s properties
var message = 'John’s properties are: ' + properties.join(', ');
document.write(message);
best way using Object.keys();
example : for getting multi variables names in global scope
// multi variables for testing
var x = 5 , b = true , m = 6 , v = "str";
// pass all variables you want in object
function getVarsNames(v = {}){
// getting keys or names !
let names = Object.keys(v);
// return array contain all names of variables
return names;
}
// testing if that work or not
let VarsNames = getVarsNames({x , b , m , v});
console.log(VarsNames); // output is array [x , b , m , v]
This worked using Internet Explorer (9, 10 and 11), Google Chrome 5:
var myFirstName = "Danilo";
var varName = Object.keys({myFirstName:0})[0];
console.log(varName);
Browser compatibility table:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Object/keys
For those who would like to print variableName and variableValue for debugging purposes, here is a function:
const printNameValue = (v)=> {
var varName = (v).toString().replace(/[ |\(\)=>]/g, '')
var varValue = (v)()
// neat : console.log(varName,varValue);
// with some coloring :
console.log("\033[1;96m[\033[1;33m " + varName + " :\033[0;0m " + varValue+"\033[1;96m ]\033[0;0m");
}
Example:
const myNiceVariable = 1234
call:
printNameValue(()=> myNiceVariable )
result:
You can reflect on types in javascript and get the name of properties and methods but what you need is sth like Lambda Expressions Trees in .NET, I think it's not be possible due to dynamic nature and lack of static type system in javascript.
I needed this, don't want to use objects, and came up with the following solution, turning the question around.
Instead of converting the variable name into a string, I convert a string into a variable.
This only works if the variable name is known of course.
Take this:
var height = 120;
testAlert(height);
This should display:
height: 120
This can be done like this:
function testAlert(ta)
{
a = window[ta];
alert(ta + ': ' + a);
}
var height = 120;
testAlert("height");
// displays: height: 120
So I use the string "height" and turn that into a variable height using the window[] command.
When having a function write a function that changes different global variables values it is not always myfirstname it is whatever happens to be passing through. Try this worked for me.
Run in jsfiddle
var jack = 'jill';
function window_getVarName(what)
{
for (var name in window)
{
if (window[name]==what)
return(name);
}
return("");
}
document.write(window_getVarName(jack));
Will write to the window 'jack'.
I've created this function based on JSON as someone suggested, works fine for my debug needs
function debugVar(varNames){
let strX = "";
function replacer(key, value){
if (value === undefined){return "undef"}
return value
}
for (let arg of arguments){
let lastChar;
if (typeof arg!== "string"){
let _arg = JSON.stringify(arg, replacer);
_arg = _arg.replace('{',"");
_arg = _arg.replace('}',"");
_arg = _arg.replace(/:/g,"=");
_arg = _arg.replace(/"/g,"");
strX+=_arg;
}else{
strX+=arg;
lastChar = arg[arg.length-1];
}
if (arg!==arguments[arguments.length-1]&&lastChar!==":"){strX+=" "};
}
console.log(strX)
}
let a = 42, b = 3, c;
debugVar("Begin:",{a,b,c},"end")
If you're looking for something quick and dirty, this might work:
var zox = 150;
cl("zox");
function cl(c) {
console.log(c + ': ' + this[c]); // zox: 150
}
No, there is not.
Besides, if you can write variablesName(myFirstName), you already know the variable name ("myFirstName").

Converting a string to a javascript associative array

I have a string
string = "masterkey[key1][key2]";
I want to create an associative array out of that, so that it evaluates to:
{
masterkey: {
key1: {
key2: value
}
}
}
I have tried this:
var fullName = string;
fullName = fullName.replace(/\[/g, '["');
fullName = fullName.replace(/\]/g, '"]');
eval("var "+fullName+";");
But I get the error: missing ; before statement with an arrow pointing to the first bracket in ([) "var masterkey["key1"]["key2"];"
I know that eval() is not good to use, so if you have any suggestions, preferably without using it, I'd really appreciate it!
Not the most beautiful, but it worked for me:
var
path = "masterkey[key1][key2]",
scope = {};
function helper(scope, path, value) {
var path = path.split('['), i = 0, lim = path.length;
for (; i < lim; i += 1) {
path[i] = path[i].replace(/\]/g, '');
if (typeof scope[path[i]] === 'undefined') {
scope[path[i]] = {};
}
if (i === lim - 1) {
scope[path[i]] = value;
}
else {
scope = scope[path[i]];
}
}
}
helper(scope, path, 'somevalue');
console.log(scope);
demo: http://jsfiddle.net/hR8yM/
function parse(s, obj) {
s.match(/\w+/g).reduce(function(o, p) { return o[p] = {} }, obj);
return obj;
}
console.dir(parse("masterkey[key1][key2]", {}))
Now try this
string = "masterkey[key1][key2]";
var fullName = string;
fullName = fullName.replace(/\[/g, '[\'');
fullName = fullName.replace(/\]/g, '\']');
document.write("var "+fullName+";");
1) When using eval, the argument you provide must be valid, complete javascript.
The line
var masterkey["key1"]["key2"];
is not a valid javascript statement.
When assigning a value to a variable, you must use =. Simply concatenating some values on to the end of the variable name will not work.
2) var masterkey = ["key1"]["key2"] doesn't make sense.
This looks like an attempt to assign the "key2" property of the "key1" property of nothing to masterkey.
If you want the result to be like the example object you give, then that is what you need to create. That said, parsing the string properly to create an object is better than using regular expressions to translate it into some script to evaluate.

Categories

Resources