JavaScript interview question

In JavaScript, what is the difference between var x = 1 and x = 1?

Answer

var x = 1

  • Allowed in 'strict mode'.
  • The var statement declares a function-scoped or globally-scoped variable, optionally initializing it to a value.
  • Variables declared using var inside a { } block can be accessed from outside the block.
  • Variables defined using var inside a function are not accessible (visible) from outside the function.
  • Duplicate variable declarations using var will not trigger an error, even in strict mode, and the variable will not lose its value unless another assignment is performed.
var x = 1;

if (x === 1) {
  var x = 2;

  console.log(x);
  // expected output: 2
}

console.log(x);
// expected output: 2
var x = 5; // global
function someThing(y) {
  var x = 3; // local
  var z = x + y;
  console.log(z);
}
someThing(4); // 7
console.log(x); // 5

x = 1

  • Not allowed in 'strict mode'.
  • Undeclared Variables like: x = 1 is accessible in: (Block scope - Function scope - Global scope)
  • Outside of strict mode, however, if you assign a value to a name that has not been declared with let, const, or var, you'll end up creating a new global variable. It will be global no matter how deeply nested within functions and blocks your code is, which is almost certainly not what you want, is bug-prone, and is one of the best reasons for using strict mode!
  • Global variables created in this accidental way are like global variables declared with var: they define properties of the global object.
  • Unlike the properties defined by proper var declarations, these properties can be deleted with the delete operator.
  • Not recommended.
var x = 5; // global
function someThing(y) {
  x = 1; // still global!
  var z = x + y;
  console.log(z);
}
someThing(4) // 5
console.log(x) // 1

Example:

{
  console.log(x + y); // NaN
  var x = 1;
  var y = 2;
}
{
  console.log(x + y); // Uncaught ReferenceError: x is not defined
   x = 1;
   y = 2;
}


 

 var x = 1x = 1
Strict mode
Block scope
Function scope
Global scope
Hoisting
Reassigning

More Technical Interview Topics