Jump to content

Question about using the DOM


Go to solution Solved by trq,

Recommended Posts

Hey guys, I am totally new to Javascript and  was going through some script examples on the web. I came across "Changing the DOM"

 

 

My questions is how come var was put in front of "mainContent" but not "mainTitle"

 var mainContent = document.getElementById("mainContent");
mainContent.setAttribute("align", "right");

mainTitle = document.getElementById("mainTitle"); // Why is there no var put in front?
console.log(mainTitle.innerHTML);

Below is the HTML code..

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=UTF-8" />
<title>Come Explore California</title>
<link href="_css/main.css" rel="stylesheet" type="text/css" />
</head>
<body id="home">
<div id="wrapper">
  <div id="header">
    <h1><a id="mainTitle" href="index.htm" title="Return to the home page">Welcome to Explore California!</a></h1>
  </div>
  <div id="mainNav">
    <ul id="homeNav">
      <li><a href="#" title="Explore our tours" class="tours">Tours</a></li>
      <li><a href="#" title="What we think" class="mission">Mission</a></li>
      <li><a href="#" title="Contact and support" class="contact">Contact</a></li>
      <li><a href="#" title="Guidance and planning" class="resources">Resources</a></li>
      <li><a href="#" title="Join our community" class="explorers">Explorers</a></li>
    </ul>
</div>
  <div id="mainContent">
    <p id="findTour"><a href="#">Find a tour!</a></p>
    <h1>Explore our world your way</h1>
    <p>At Explore California, we want you to do just that, explore our wild and wonderful state any way you please. Our tour packages are as diverse as California itself and are designed to let you experience our beautiful state in a whole new way. Whether you want to take guided tours through stunning wine country, or set your own agenda as you bike along miles of breathtaking Pacific coastline, we have something for everyone. <em>Come explore.</em></p>
    <div id="spotlight">
      <h2><img src="_images/cycle_logo.gif" width="165" height="120" alt="cycle california" class="articleImage" />Tour Spotlight</h2>
      <p>This month's spotlight package is Cycle California. Whether you are looking for some serious downhill thrills to a relaxing ride along the coast, you'll find something to love in Cycle California. <a href="tours_cycle.htm" title="Explore cycling" class="accent">Tour Details</a></p>
 </div>
    </div>
  <div id="sidebar">
      <div id="specials" class="callOut">
        <h1>Monthly Specials</h1>
        <h2 class="top"><img src="_images/calm_bug.gif" width="75" height="75" alt="California Calm" />California Calm</h2>
        <p>Day Spa Package <br />
          <a href="#">$250</a>        </p>
        <h2><img src="_images/desert_bug.gif" width="75" height="75" alt="From desert to sea" />From Desert to Sea</h2>
        <p>2 Day Salton Sea <br />
          <a href="#">$350</a></p>
        <h2><img src="_images/backpack_bug.gif" width="75" height="41" alt="Backpack Cali" />Backpack Cali</h2>
        <p>Big Sur Retreat <br />
          <a href="#">$620</a></p>
      </div>
      <div id="trivia" class="callOut">
        <h1>Did You Know?</h1>
        <p>California produces over 17 million gallons of wine each year!</p>
      </div>
    </div>
  <div id="footer">
<div id="footerMenu">
  <h3>Quick Nav</h3>
    <ul id="quickNav">
      <li><a href="#" title="Explore our tours">Tours</a></li>
      <li><a href="#" title="What we think">Mission</a></li>
      <li><a href="#" title="Contact and support">Contact</a></li>
      <li><a href="#" title="Guidance and planning">Resources</a></li>
      <li><a href="#" title="Join our community">Explorers</a></li>
    </ul>
</div>
  <div id="footerBody">
  <div id="footerMidCol">
      <h3><a href="#">FAQ</a></h3>
      <p>Find out more about our tours</p>
      <h3><a href="#">Support</a></h3>
      <p>Need help? It's just a click away!</p>
      <h3><a href="#">Legal Disclaimer</a></h3>
    </div>
    <div id="footerRightCol">
      <h1>Explore California</h1>
      <p>5605 Nota Street<br />
        Ventura, CA 93003</p>
      <p class="phone">866.555.4310</p>
    </div>
</div>
  </div>
</div>
<script src="script.js">
</script>
</body>
</html>

Edited by eldan88
Link to comment
https://forums.phpfreaks.com/topic/283571-question-about-using-the-dom/
Share on other sites

  • Solution

Just laziness or forgetfulness I should imagine. The difference between using var and not using var in this context is very subtle and not likely intended.

 

In simple terms. In the above example, it really doesn't matter / make a difference.

var declares the variable for the current scope. The main purpose of doing it is to ensure you are not overwriting a variable in a higher scope. Example:

 

var foo = 'bar';

function doSomething() {
  foo = 'blah';
}
console.log(foo);
doSomething();
console.log(foo);
output:

bar
blah
In this example, foo is first declared in the global scope. Then within function doSomething(), the variable foo is assigned another value. Because foo was declared in the global scope, and there is not a var prefix in the function, javascript will assign the new value "blah" to that global variable. This is because javascript sees that you are doing something with a variable and moves up the scope chain to find where that variable was declared, and reference it when it finds it.

 

Now, if I had NOT declared foo in the higher scope, javascript would have implicitly declared it within the function's scope, even without the var prefix. But this is not something you should depend on or code for. You should always declare you locally scoped variables, to avoid the dangers of overwriting variables in a higher scope. I have seen this happen time and time again with "throwaway/temp" local variables. For example, someone just picks a random variable to use as an incrementer for a loop, but doesn't declare it.. only to find out later that it overwrote some 3rd party app's namespace in the global scope. And this happens more often than you think, because 3rd party vendors are notorious for using short namespaces to condense their code as much as possible, and coders are notorious for using short namespaces for "throwaway/temp" vars.

 

For example, Adobe Marketing Analytics is an enterprise level site/visitor tracking solution (it's like Google Analytics but has a LOT more bells and whistles but costs a LOT of money). It's default namespace is s. And until relatively recently, it didn't have an easy way to change that namespace. Now consider this code:

 

<script type='text/javascript'>
function getPageName() {
  s=location.pathname.replace(/^\/|\/$/g,'').split('/').pop();
  return s;
}
</script>

<!-- watered down version of Adobe code -->
<script type='text/javascript' src='s_code.js'></script>
<script type='text/javascript'>
s.pageName=getPageName();
s.prop1='en';
s.t();
</script>
All "that could have been written better" responses aside, this demonstrates the problem of namespace overwriting. s is declared within s_code.js and is Adobe's object namespace. Some custom tracking variables are then set, and s.t() is the "trigger" function that makes the tracking request happen. But see how we delegate popping s.pageName to some function (which is pretty common). Because function getPageName() did not first declare s locally, javascript will overwrite s in the global scope, and you will end up getting a javascript error from the rest of the code which attempts to use s as an object with established properties and methods.

 

A more realistic example (that I have seen happen quite a number of times) is when the Adobe library script is included in the head tag, and the custom code and trigger is placed on the bottom of the page before closing body tag (again, pretty common setup). That leaves a whole lot of space inbetween for some other random js snippet or 3rd party library to be placed and accidentally overwrite the s namespace. The most common thing I've seen is js loaded script includes, which look something like this:

 

(function() {
    var s = document.createElement('script');
    s.type = "text/javascript";
    s.src = "https://www.site.com/script.js";
    var st = document.getElementsByTagName('script')[0];
    st.parentNode.insertBefore(s, st);
})();
This is more or less the standard way of using js to include a script (unless you are using a js library like jQuery). This example is fine, because variables are declared and there's closure and all that. However, I have seen some people not wrap it in an anonymous function, and I have seen some people not declare their variables before assigning to them. And s is a common var coders use in this scenario, since it's short for "script". You don't have to use it.. but it's a common convention to name variables after what they stand for.

 

Anyways, TL:DR; version: Unless you are intentionally referencing a higher scoped variable, always make sure to declare the local scoped vars you use, to make sure you don't accidentally overwrite some other higher scoped variable. Actually, it is a rare case in which it's a good idea to reference higher scoped variables in the first place. Ideally, you should be passing them to the function and returning the value. There are exceptions to this (e.g. referencing the window or document object), and also some cases where you're working with what you have and can't touch other code (the "lesser evil" scenarios), but usually you should avoid doing that.

Using var in front of JS variables ensures:

 

1. That you are following a good programming practice;

 

2. The creation of a scope of the variable (As Josh above pointed out);

 

3. Better readability, since seeing var in front of a variable automatically means that this is the first instance of this variable and you are not over-writing another one;

 

4. That you are a good programmer;

 

Kind of like my in Perl, although not that strict in relation to the scope. I wish they had made var mandatory in JS just like my had become in Perl 5.12 + 

 

Do something, Mr Eich! 

This thread is more than a year old. Please don't revive it unless you have something important to add.

Join the conversation

You can post now and register later. If you have an account, sign in now to post with your account.

Guest
Reply to this topic...

×   Pasted as rich text.   Restore formatting

  Only 75 emoji are allowed.

×   Your link has been automatically embedded.   Display as a link instead

×   Your previous content has been restored.   Clear editor

×   You cannot paste images directly. Upload or insert images from URL.

×
×
  • Create New...

Important Information

We have placed cookies on your device to help make this website better. You can adjust your cookie settings, otherwise we'll assume you're okay to continue.