-2

I am confused why you can't just say name = "Bob" instead of var name = "Bob". Also, is there a way to set a variable to itself but with some changes.

Such as: name = name + "and"

drewteriyaki
  • 320
  • 1
  • 3
  • 12

2 Answers2

0

From MDN: (Emphasis mine)

Variable declarations, wherever they occur, are processed before any code is executed. The scope of a variable declared with var is its current execution context, which is either the enclosing function or, for variables declared outside any function, global.

Assigning a value to an undeclared variable implicitly creates it as a global variable (it becomes a property of the global object) when the assignment is executed.

Source

Regarding your second point, yes, you can use the variable you are assigning to in the calculation as you described. The following code is valid:

var test = "foo"
test = test + "bar"
alert(test) // foobar
Community
  • 1
  • 1
TimoStaudinger
  • 41,396
  • 16
  • 88
  • 94
0

var are containers for storing values, like numbers, objects, strings etc.

Examples:

var number_variable = 1
var string_variable = ""
var object_variable = {}
var function_variable = function() {
  alert("Hi!")
}

Note that executing var inside the function cannot be viewed in global.

Example:

function myFunc() {
var string = "Hey"
}
myFunc()
console.log(string)

It will not log the string "Hey" in the console and will return an error!

---

You can combine variables by using +!

Examples:

var a = "Hey "
var b = "Mom!"
var c = a + b // Hey Mom!
var d = 1
var e = 2
var f = d + e // 3
var g = a + d // Hey 1
var h = e - d // 1
var i = 4 / e // 2
var j = 3 * e // 6
shunz19
  • 495
  • 4
  • 13