Home Calling variables outside of a function in javascript
Reply: 1

Calling variables outside of a function in javascript

Jude Aquino
1#
Jude Aquino Published in 2017-09-13 08:21:33Z

I'm new to javascript and firebase. I would just like to ask if there is a chance to call my variables outside of my function?

Here is my sample code:

function gotData (data) {
  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)
  console.log(keys)
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i]
    var name = promotions[k].promotionName
    var description = promotions[k].description
    var validityFrom = promotions[k].validityPeriodFrom
    var validityTo = promotions[k].validityPeriodTo
    var dateCreated = promotions[k].dateCreated
    var dateUpdated = promotions[k].dateUpdated
    console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
  }
}

Can I call name, description, validityFrom, etc outside of the function gotData? I'll appreciate a help. Thank you in advance! :)

Jigar Shah
2#
Jigar Shah Reply to 2017-09-13 08:44:14Z

Define variable as global variable

//above function
var name, description, validityFrom, validityTo, dateCreated, dateUpdated;
function gotData (data) {
  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)
  console.log(keys)
  for (var i = 0; i < keys.length; i++) {
    var k = keys[i]
    name = promotions[k].promotionName
    description = promotions[k].description
    validityFrom = promotions[k].validityPeriodFrom
    validityTo = promotions[k].validityPeriodTo
    dateCreated = promotions[k].dateCreated
    dateUpdated = promotions[k].dateUpdated
    console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)
  }
}
// now you can access variables here
console.log(name, description, validityFrom, validityTo, dateCreated, dateUpdated)

EDIT

You can create an array to get all variables as you may have multidimensional data

var objData = [];
function gotData (data) {

  console.log(data.val())
  var promotions = data.val()
  var keys = Object.keys(promotions)

  for (var i = 0; i < keys.length; i++) {
    var tempObj = [];
    var k = keys[i]
    tempObj['promotionName'] = promotions[k].promotionName;
    tempObj['description'] = promotions[k].description;
    tempObj['validityPeriodFrom'] = promotions[k].validityPeriodFrom;
    tempObj['validityPeriodTo'] = promotions[k].validityPeriodTo;
    tempObj['dateCreated'] = promotions[k].dateCreated;
    tempObj['dateUpdated'] = promotions[k].dateUpdated;

    objData.push(tempObj);
  }
  console.log(objData)
}
You need to login account before you can post.

About| Privacy statement| Terms of Service| Advertising| Contact us| Help| Sitemap|
Processed in 0.305232 second(s) , Gzip On .

© 2016 Powered by cudou.com design MATCHINFO