Welcome to the Treehouse Community

Want to collaborate on code errors? Have bugs you need feedback on? Looking for an extra set of eyes on your latest project? Get support with fellow developers, designers, and programmers of all backgrounds and skill levels here with the Treehouse Community! While you're at it, check out some resources Treehouse students have shared here.

Looking to learn something new?

Treehouse offers a seven day free trial for new students. Get access to thousands of hours of content and join thousands of Treehouse students and alumni in the community today.

Start your free trial

JavaScript

Code runs when defining a variable?

I was watching one of the tutorials, and I realized when the instructor defined a variable like this,

var http = require("http")

the code in the variable runs. Why is this? I always thought when you defined a variable, you have to use it somewhere else to access what is stored in it. Thanks if someone could clear this up for me.

1 Answer

I am thinking that reason why you can do this is so you can write

var http = require("http");

// instead of having to write

var http;
http = require("http");

Any time you write a function and include parentheses at the end, you are telling the browser to run that function, and if the function returns a value that you plan to reuse, this is one of the ways you would do.

Below are some examples of how you can declare the value for a new variable:

// all these variables will equal 4

// simply declaring a variable with a constant value
var w = 4;

// perform operation here. If it was more complex, we might want to create a function for it.                                           
var x = 2 + 2;  

// parentheses will call this anonymous function right here and return 4.
var y = function(){ return 2 + 2; }(); 

// call a function and return value will be the variable's value.
var z = add(2, 2);                                

function add(num1, num2) {
  return num1 + num2;
}

I hope this helps! :D

Thank you!