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.

Image of Datadog

The Future of AI, LLMs, and Observability on Google Cloud

Datadog sat down with Google’s Director of AI to discuss the current and future states of AI, ML, and LLMs on Google Cloud. Discover 7 key insights for technical leaders, covering everything from upskilling teams to observability best practices

Learn More

Top comments (0)

Image of Datadog

The Essential Toolkit for Front-end Developers

Take a user-centric approach to front-end monitoring that evolves alongside increasingly complex frameworks and single-page applications.

Get The Kit

👋 Kindness is contagious

Immerse yourself in a wealth of knowledge with this piece, supported by the inclusive DEV Community—every developer, no matter where they are in their journey, is invited to contribute to our collective wisdom.

A simple “thank you” goes a long way—express your gratitude below in the comments!

Gathering insights enriches our journey on DEV and fortifies our community ties. Did you find this article valuable? Taking a moment to thank the author can have a significant impact.

Okay