Skip to content
Drempd Logo
  • home
  • portfolio
  • web design journal
  • blog
    • adventure
    • san diego
    • projects
    • website design
    • code notes
  • contact
Blog Web Dev Namespacing in Javascript

Namespacing in Javascript

By Forrest Smith - Drempd.com

So the other night I was working on some fancy script. It didn't work. After a bit of investigation, it turns out that one of the function names was already being used by a different function. Bummer. Of course this is why people use namespacing, to avoid problems such as this. So, here's how to write a sample bit of code to utilize namespacing in javascript:

 var myApp = (function(){
     var numericval = 10;

     return{
          moveLeft: function(){
               alert('left:'+numericval);
          },
          moveRight: function(){
               alert('right');
          }
     };
})();

$(document).ready(function(){
     $('.left').click(myApp.moveLeft);
});

Or to call it from other javascript code:

      myApp.moveLeft();

I don't really care for nesting all of my functions within the namespace declaration, so you can also do something like the following, outside of the namespace:

var myApp = (function(){
//some code in here
return{} //Make sure to include this line
})();

myApp.testFunction = function(){
//some code here
}

Posted on April 1, 2014December 26, 2023 in Web Dev

Leave a Reply Cancel reply

Your email address will not be published. Required fields are marked *

I love to create and explore. Whether building a website or app, taking a long walk through the mountains, or playing with a random idea, I've found that there will never be enough time to experience it all. But that won't stop me from trying.

Web Design & Development

  • Portfolio
  • San Diego Website Design
  • Custom Web Design
  • Responsive Web Design
  • Website Maintenance
  • Freelance Web Designer
  • Web Design Posts
  • Website Checklist

Projects

  • Zindash
  • Opti
  • Saphire CSS
  • Ergo Blocks

Blog

  • Adventure
  • San Diego
  • Projects
  • Website Design
  • Arch & Urban
  • Technology
  • Code Notes

About

  • Bluesky
  • Resume
  • Contact
drempd | san diego, ca
© 2026 Drempd All rights reserved.