DEV Community

Heru Hartanto
Heru Hartanto

Posted on

2 1

Create Variable without var

Once upon a time, there are creature that destructive, seeking a clumpsy developer to lose their guard and attack them with their claw.

The var is very wild because var has no block scope which mean they are "the beast" that visible outside blocks. here some example:

  if(true){
    var a = 'var is wild' 
  }
  alert(a);
Enter fullscreen mode Exit fullscreen mode

since var ignore blocks, var a will become global variable and browser will show alert that contain variable a value.

var also can't be block-or and loop-local which mean it's just ignore for loop block.

if you're using var inside function, then var become a function-level variable

  function sayHi() {
    if (true) {
      var a = "Hi";
    }

    alert(a); // works
  }

  sayHi();
  alert(a); // ReferenceError: a is not defined
Enter fullscreen mode Exit fullscreen mode

when we create var and redeclare it below the first variable, they will ignore the old one and use newest variable value

var user = "Pete";
var user = "John"; // this "var" does nothing (already declared)
// ...it doesn't trigger an error

alert(user); // John
Enter fullscreen mode Exit fullscreen mode

remember when I mention that var is a global variable, it's also mean that they are able to declare below their use, so technically move them above

function sayHi() {
  phrase = "Hello";

  alert(phrase);

  var phrase;
}
sayHi();
Enter fullscreen mode Exit fullscreen mode

as same as with

function sayHi() {
  var phrase;

  phrase = "Hello";

  alert(phrase);
}
sayHi();
Enter fullscreen mode Exit fullscreen mode

because of this behaviour, I suggest you to use let and cost instead of var they are more modern and clean in term of block.

Sentry image

See why 4M developers consider Sentry, “not bad.”

Fixing code doesn’t have to be the worst part of your day. Learn how Sentry can help.

Learn more

Top comments (0)

Billboard image

The Next Generation Developer Platform

Coherence is the first Platform-as-a-Service you can control. Unlike "black-box" platforms that are opinionated about the infra you can deploy, Coherence is powered by CNC, the open-source IaC framework, which offers limitless customization.

Learn more

👋 Kindness is contagious

Please leave a ❤️ or a friendly comment on this post if you found it helpful!

Okay