-3

A newbie learning javascript :)

This is my html page and the associated js code

<!DOCTYPE html>
<html>
<head>
<title> A Basic Function </title>
<link rel="stylesheet" href="css/c03.css" />
</head>
<body>
<h1>Travelworth</h1>
<div id="message">Welcome to our site!</div>
<script src="js/basic-function.js"></script>
</body>
</html>

basic-function.js

var msg="A New Message"; //Line 1
var msg="A Second Message";//Line 2

function updatemessage()
{

var e = document.getElementById('message');
e.textContent = msg;
}

updatemessage();

Q1:-

This webpage displays the message from the Line2 instead of Line1.

I am guessing this is because the "msg" variable declared in Line 2 is considered the "latest" and the interpreter has proceeded with that.

Is my assumption right ?

Q2:-

If that is the case, then there will be instances where a webpage may utilize multiple js files written by different people.

How the naming conflict will be handled on global variables between these two different js files referenced in the same webpage ?

Can someone explain ?

Rainmaker
  • 127
  • 5
  • 1
    why use the global names? why not create an object and assign properties to it/ – gurvinder372 Feb 15 '16 at 08:36
  • What ever language you will use this is the basic rule that two variable names must be different. First variable value will be override by the last value. You must know the scope logic. – Pallavi Feb 15 '16 at 08:40
  • I am interested to know how the conflict situation will be handled by the interpreter – Rainmaker Feb 15 '16 at 08:40
  • checkout for creating namespaces in js, lookup closures in JS. I guess you might be looking for them – joyBlanks Feb 15 '16 at 08:45

2 Answers2

0

JavaScript has two scopes: global and local. A variable that is declared outside a function definition is a global variable, and its value is accessible and modifiable throughout your program. A variable that is declared inside a function definition is local. It is created and destroyed every time the function is executed, and it cannot be accessed by any code outside the function. JavaScript does not support block scope (in which a set of braces {. . .} defines a new scope), except in the special case of block-scoped variables.

For block-scoped variables, see What's the difference between using "let" and "var" to declare a variable?

For Q1, see What is the purpose of the var keyword and when to use it (or omit it)?

Community
  • 1
  • 1
enkryptor
  • 1,574
  • 1
  • 17
  • 27
0

You guess right. It is bad idea to declare two variables with same name. Good written third party libraries do not use global variables - they use local, or encapsulate multiple variables in one.

S. Nadezhnyy
  • 582
  • 2
  • 6