var in JavaScript

2026年8月16日4 次浏览来源:Dev.to阅读原文

is one of the ways to create a variable in JavaScript.

A variable is a place to store a value, like a name or a number. is mostly seen in old JavaScript code, written before

2015.

Today most people use and instead, but it still helps to know , especially when reading old code.

Creating a Variable Here, stores and stores .

We Can Change the Value The output is .

The value inside got updated.

We Can Also Create it Again We can create the same variable a second time with , and JavaScript does not give an error.

The output is .

It just overwrites the old value.

It Works Across the Whole Function A block is a small part of code inside , like an statement. does not care about these small blocks, it only cares about the function.

Even though was created inside the part, we can still use it outside the , as long as we are inside the function.

Hoisting You might expect an error here, but the output is .

This is because JavaScript moves the declaration to the top before running the code.

This is called hoisting.

Why var Isn't Used Much Now Most people use and instead of , because can cause confusing bugs like accidental redeclaration and hoisting. is used when the value can change, and is used when it should not change.

In Short was the first way to create variables in JavaScript.

It can be changed, redeclared, and it works across the whole function instead of one block.

Once you understand , and become easier to learn.

分享