0

How can we print all the variables at once in javascript?? For example, consider the following code :-

var str1 = "Programming is fun";
var str2 = "Programming is cool";
document.write(str1);
document.write(str2);

Here, I have two variables and i wrote document.write() statement two times. If I have 1000 such variables, then do i need to write document.write() statement 1000 times?? How do I print these 1000 variables?? Is there anyway to print the values according to data type (in this case, the data type is var)???

Gopal1216
  • 421
  • 3
  • 7
  • 14
  • If you declare them with `var` there is no good way, as the variables are either local or properties of `window`. If you declare them as the properties of an object or in an array, you can use the for-in loop. – PurkkaKoodari Feb 05 '14 at 16:06
  • You can store them in an array and loop the array, the data type is also not `var` – tymeJV Feb 05 '14 at 16:06
  • `var` is not a "data type". – Bob Gilmore Feb 05 '14 at 16:07
  • @Pietu1998 if they are properties of `window` then why can't you iterate over them? e.g. https://stackoverflow.com/questions/2934787/view-list-of-all-javascript-variables-in-google-chrome-console#2934812 – gvee Feb 05 '14 at 16:07
  • @gvee only if you're in the global scope of the host environment. – Benjamin Gruenbaum Feb 05 '14 at 16:08
  • @gvee If you iterate over the `window` properties you also get a ton of `window` properties. (I tried, ~200.) – PurkkaKoodari Feb 05 '14 at 16:15

4 Answers4

2

The data type isn't var. In JavaScript the var keyword is used to indicate that you're declaring a new variable in the current scope, it doesn't communicate anything about the variable's type.

If you want an unknown number of variables to print out, use an array:

var arr = [];
arr.push("Programming is fun");
arr.push("Programming is cool");

for(var i = 0, l = arr.length; i < l; i++) {
    document.write(arr[i]);
}

You can alternatively initialise the array like this:

var arr = ["Programming is fun", "Programming is cool"];

then use the same for loop to iterate through and write them out.

Anthony Grist
  • 38,173
  • 8
  • 62
  • 76
  • If you're making it shorter, consider `arr.forEach(document.write.bind(document));` – Benjamin Gruenbaum Feb 05 '14 at 16:12
  • Thank you for your answer. But I wanted to know if we can print according to variables (var). If any new variable is declared, then it must be automatically printed. Something like that. Please help!! – Gopal1216 Feb 08 '14 at 08:47
0

If I have 1000 such variables, then do i need to write document.write() statement 1000 times

Either that or concatenate the strings together with +.

If you've got multiple related variables, then relate them programatically. Put them in an array (if they are sequential) or an object (if they are not). You can then loop over that data structure.

Is there anyway to print the values according to data type (in this case, the data type is var)

var is not a data type. It is a keyword that sets the scope of a variable.

The typeof operator will tell you the data type (see also instanceof), but you'll still need a way to apply it to each piece of data you want to deal with (so we are back to arrays/objects).

Quentin
  • 914,110
  • 126
  • 1,211
  • 1,335
  • Thank you for your answer. But I wanted to know if we can print according to variables (var). If any new variable is declared, then it must be automatically printed. Something like that. Please help!! – Gopal1216 Feb 08 '14 at 08:46
  • No, you can't. That is why you should organise your data in a sensible structure. – Quentin Feb 08 '14 at 08:52
0

You'll have to create a data structure, most likely an array, fill that array up with your variables, then loop over that and output them. Something like this.

var myArray = ['programming is fun', 'programming is cool', 'programming is lame'];
for(var i = 0; i < myArray.length; i++){
  document.write(myArray[i]);
}
Tyler McGinnis
  • 34,836
  • 16
  • 72
  • 77
  • `myArray.forEach(document.write.bind(document));` – Benjamin Gruenbaum Feb 05 '14 at 16:09
  • Thank you for your answer. But I wanted to know if we can print according to variables (var). If any new variable is declared, then it must be automatically printed. Something like that. Please help!! – Gopal1216 Feb 08 '14 at 08:48
0

METHOD 1

Based on your recent comments, this will let you output variables as you create them, and also carry on using variables in the way that you are currently used to, without getting into complicated data store creation.

Here is a working example, try it out

The code:

// include this function once in your code, at the top of the script, 
// and outside of any other functions. 

function v(value) {
    var outputText = (typeof value === "object" && value.constructor === Object && window.JSON) ? JSON.stringify(value) : value;
    document.body.appendChild(document.createTextNode(outputText));
    document.body.appendChild(document.createElement("br"));
    return value;
}

// When you create variables, use this function to assign and output the value.
// So instead of:   var someVariable = "someValue";
// Use:             var someVariable = v("someValue");
// this will output the value to the document, 
// and still assign the variables as you'd expect. 



// create and output a "greeting" variable
var greeting = v("Hello There!");


// create and output an array of primary colours
var primaries = v(["red", "green", "blue"]); 


// alert the greeting - alerts: "Hello there!"
alert(greeting);

METHOD 2

This is more complicated but also more useful. It creates a data store object which both provides neat storage for your variables, and a few methods to set them with output, get them for use, delete them and output them all again. May be overkill for you but was great fun to write! :)

Here is a working example

The code:

// An object in which to store variables, which also writes variables to a given element as you create them.
// Include this code at the top of your javascript. 

var VariableStore = function(outputElement) {
    this.store = {};
    this.outputElement = outputElement;
};
VariableStore.prototype = {
    create : function(key, value) {
        this.store[key] = value;
        this.output(key);
    },
    get : function(key) {
        return this.store[key];
    },
    destroy : function(key) {
        delete this.store[key];
    },
    output : function(key) {
        var value = this.store[key];        
        var outputText = (typeof value === "object" && value.constructor === Object && window.JSON) ? JSON.stringify(value) : value;
        this.outputElement.appendChild(document.createTextNode(outputText));
        this.outputElement.appendChild(document.createElement("br"));
    },
    outputAll : function() {
        for(var key in this.store) {
            this.output(key);
        }
    }
};


// Here's how to use the object above.

// 1. Create a new instance of VariableStore, here called v. This only needs to be done once in your script, just underneath the VariableStore object above.

var v = new VariableStore(document.body);


// 2. This creates three new variables. They will be automatically outputted to the output element when they are created. This code can go anywhere in your script underneath the first two steps.
// The arguments are: v.create("yourVariableName", "Your Variable Contents");

v.create("myName", "Zougen Moriver"); // a simple String
v.create("primaryColours", ["red", "green", "blue"]); // an array of primary colours
v.create("someObject", {"greeting":"Hi There!"}); // A friendly object literal


// if you need to delete a variable again, this deletes the primaryColours array for example

v.destroy("primaryColours");



// 3. You can retreive any of the variables you create using v.get("variableName"). Here, we retreive the "name" variable we just created and alert it.

alert(v.get("myName"));



// 4. If you want to output all the variables again, use v.outputAll();

v.outputAll();
Josh Harrison
  • 5,927
  • 1
  • 30
  • 44
  • Thank you for your answer. But I wanted to know if we can print according to variables (var). If any new variable is declared, then it must be automatically printed. Something like that. Please help!! – Gopal1216 Feb 08 '14 at 08:47
  • These *are* variables. `var` declares that "the following variable can only be accessed from inside the same scope", which unless your `var` statement is inside a function, will be the global `window` object. Please read about [scopes here](http://bonsaiden.github.io/JavaScript-Garden/#function.scopes). In my example, the variables are explicitly created as properties of a different object (`store`). `var` is not needed. This keeps them all together in one place. As for automatic printing, I'm curious to know why you would need to do that? – Josh Harrison Feb 08 '14 at 13:14
  • I've updated my answer with a new idea based on your latest comment. I recommend checking out option 1. – Josh Harrison Feb 08 '14 at 14:12
  • Thank you very much. That was a lot helpful. Frankly speaking, there was no particular project or something like that in which I wanted to implement this. It just came to my mind and I tried coding it out but failed. So I posted this qn. Thanks a ton for ur answer. This is exactly what I needed. – Gopal1216 Feb 09 '14 at 13:56
  • Great. Glad it's helped you, and be sure to accept the answer, as it has answered your question. – Josh Harrison Feb 09 '14 at 14:12
  • I'm new to this site. Can you tell me where I can accept the answer as it has answered my qn. – Gopal1216 Feb 10 '14 at 17:17
  • Sure. Underneath the vote count on the answer, you click the 'tick'. :) – Josh Harrison Feb 10 '14 at 17:36