Javascript var

In JavaScript, var is one of the three ways to declare variables, along with let and const. Here's a detailed overview of how var works and its characteristics:



Characteristics of var:


1)  Function Scope:


     Variables declared with var are function-scoped. This means they are only accessible within the function in which they are defined. However, if declared outside a function, they become global variables.

Example
<!DOCTYPE html>
<html>
<head>
<title>Online HTML Editor</title>
</head>
<body>
<script>
function test() {
var x = 10;
console.log(x); // Outputs: 10
}
test();
console.log(x);// Error: x is not defined (x is function-scoped)
</script>
</body>
</html>

Try it yourself

 2) Re-declaration:


     You can re-declare variables using var within the same scope without any errors.

Example
<!DOCTYPE html>
<html>
<head>
<title>Online HTML Editor</title>
</head>
<body>
<script>
var name = "Alice";
var name = "Bob"; // No error, but overwrites the previous value
console.log(name); // Outputs: Bob

</script>

</body>
</html>

Try it yourself

3) Global Variables:


    When a var is declared outside any function, it becomes a property of the global object.

Example
<!DOCTYPE html>
<html>
<head>
<title>Online HTML Editor</title>
</head>
<body>
<script>
var globalVar = "I am global";
console.log(window.globalVar); // Outputs: "I am global"

</script>

</body>
</html>

Try it yourself

4) No Block Scope:


     var does not respect block scope (i.e., { ... } created by loops or conditionals). This means that variables declared with var are accessible outside of blocks, even if they are declared inside.

Example
<!DOCTYPE html>
<html>
<head>
<title>Online HTML Editor</title>
</head>
<body>
<script>
if (true) {
var num = 10;
}
console.log(num); // Outputs: 10 (even though num is inside the block)
</script>
</body>
</html>

Try it yourself

Whereisstuff is simple learing platform for beginer to advance level to improve there skills in technologies.we will provide all material free of cost.you can write a code in runkit workspace and we provide some extrac features also, you agree to have read and accepted our terms of use, cookie and privacy policy.
© Copyright 2024 www.whereisstuff.com. All rights reserved. Developed by whereisstuff Tech.