3.Scoping


#1

3.Scoping

Help , how i can return a several variables from this function to global variables?


var buildingLaundryCode, buildingPhone,buildingAddress;
function myApartment() {
	var myCoffeeMaker = 'Aeropress';
	var buildingAddress = '150 E 14th St, New York, NY';
	var myCloset = 'Extra coats in the back';
	var buildingLaundryCode = 4927;
	var myRefridgerator = 'Filled with veggies and dark chocolate.';
	var myDog = 'Nikko';
	var buildingPhone = '(481) 516-2342';
	return [buildingLaundryCode, buildingPhone,buildingAddress ];
}
myApartment();






// Do not edit the code after this line
console.log("**Apartment Building Information**");
console.log("Laundry code: " + buildingLaundryCode + "\nPhone: " + buildingPhone + "\nMailing address: " + buildingAddress);





#2

There are multiple ways to solve this issue.

Since you have global variables for buildingLaundryCode, buildingPhone, and buildingAddress, you do not need to redefined them in your function by using var.

var buildingLaundryCode, buildingPhone,buildingAddress;
function myApartment() {
	var myCoffeeMaker = 'Aeropress';	
	var myCloset = 'Extra coats in the back';        
	var myRefridgerator = 'Filled with veggies and dark chocolate.';
	var myDog = 'Nikko';
        
        buildingAddress = '150 E 14th St, New York, NY';
	buildingLaundryCode = 4927;
	buildingPhone = '(481) 516-2342';
}
myApartment();

In your example, since you are returning an array, you can also assign the returned array to a variable.

var buildingLaundryCode, buildingPhone,buildingAddress;
function myApartment() {
	var myCoffeeMaker = 'Aeropress';
	var buildingAddress = '150 E 14th St, New York, NY';
	var myCloset = 'Extra coats in the back';
	var buildingLaundryCode = 4927;
	var myRefridgerator = 'Filled with veggies and dark chocolate.';
	var myDog = 'Nikko';
	var buildingPhone = '(481) 516-2342';
	return [buildingLaundryCode, buildingPhone,buildingAddress ];
}

var result = myApartment();
buildingLaundryCode = result[0];
buildingPhone = result[1];
buildingAddress  = result[2];

or

[buildingLaundryCode, buildingPhone, buildingAddress] = result;

See here for more informtion.

Although, I would preferably return an object.

var buildingLaundryCode, buildingPhone,buildingAddress;
function myApartment() {
	var myCoffeeMaker = 'Aeropress';
	var buildingAddress = '150 E 14th St, New York, NY';
	var myCloset = 'Extra coats in the back';
	var buildingLaundryCode = 4927;
	var myRefridgerator = 'Filled with veggies and dark chocolate.';
	var myDog = 'Nikko';
	var buildingPhone = '(481) 516-2342';
	return {buildingLaundryCode, buildingPhone,buildingAddress };
}
var result = myApartment();
buildingLaundryCode = result.buildingLaundryCode;
buildingPhone = result.buildingPhone ;
buildingAddress  = result.buildingAddress;

#3

This topic was automatically closed 7 days after the last reply. New replies are no longer allowed.