pure javascript text slider that changes display of text from php - javascript

I am working on a project that has a testimony slideshow for my website. I am using php and mysql for the database. I want to use pure javascript to display the name and comment from the database. I already have the names and comments pulled from the database and stored into a javascript array. I have made it so the text displays by using setInterval and rand() to change the variable, but it does not rotate to the next image.This is my script right now.
function showComment(number) {
document.write('<p>');
document.write(unescapeHtml(js_comment[number]));
document.write('</p>');
document.write('<p>');
document.write(unescapeHtml(js_name[number]));
document.write('</p>');
}
setInterval(showComment(Math.floor(Math.random()*num_results), 2431);
js_comment[] and js_name[] are the variables with the name and comment from php num_results is the number of comments
jsfiddle for it so far jsfiddle.net/4nq2c0xb/

You would likely want to use a container and textContent / innerText, e.g.:
<p id="comment"></p>
<h3 id="name"></h3>
And then first get the elements:
var comment = document.getElementById('comment');
var name = document.getElementById('name');
And in the interval function:
comment.textContent = js_comment[number];
name.textContent = js_name[number];
https://developer.mozilla.org/en-US/docs/Web/API/Node.textContent#Browser_compatibility
http://clubajax.org/plain-text-vs-innertext-vs-textcontent/
Short update:
Not directly related to question, but some thoughts in regard to comments etc. I also register you might be in a beginner phase where basic concepts might be more important; but add it anyhow.
Note that when you have some code of some size you can also use
Code Review SE
to get input on your code. Hints and help on good and bad, how to refactor etc.
Variable scope:
If new to JavaScript this might be a bit out of scope of how your compendium are set up and where you are, but mention it as it is a rather important topic.
The first thing of concern when looking at your code is variable scope. To put it short: avoid global variables. That is variables that are accessible and modifiable from anywhere. This is highly frowned upon when it comes to production code. In short: It quickly becomes a nightmare to keep track of variables in global scope. It is prone for very ugly bugs etc. Maintaining such code, not the least for others, or your self after say 6 months, a year or what ever, also quickly makes it hard to read and so on.
How to avoid global variables in JavaScript?
In this regard there is also the need to always define variables. Not that you have not done it, but still. Personally I usually define variables in top of functions (quite a few people disagree with this, but my pref.). This way I know what variables are used, it is quick to control that it has been defined, it is a good place for a overview with comments etc.
What is the scope of variables in JavaScript?
All to note. It is important to know where variables exists. E.g. changing a global variable affects it in all functions using that variable.
Write short concise functions:
I follow the rule of thumb: “let a function do one thing, and do it well.” If a function do too much it often gets hard to maintain, it is prone for bugs, the re-usability is quickly gone etc.
Of course, sometimes I stray from this, especially if it is short example code or some quick and dirty temporary solution, testing some concept or the like; but, I have more then once also regretted this by having to use lot of time refactoring the code afterwards.
It is at least something to keep in mind.
Keep functions short.
Be very careful not to have deep nesting etc., bad:
if () {
if () {
for () {
...
Use strict mode:
What does “use strict” do in JavaScript, and what is the reasoning behind it?
Wrap your code in a strict scope:
(function(){
"use strict";
function foo() {
}
function bar() {
}
})();
Some of the advantages are described in linked answer.
Use code analysis tools:
Should I use JSLint or JSHint JavaScript validation?
This can be somewhat too much for some newcomers as it seems all the code is bad all the time ;). It takes some experience to get used to and if one do not know the language well, it can, I guess, often be hard to understand why some things are considered bad. But; it is a good way of developing good habits. Personally I have it incorporated into my editor of choice, Vim, and as such every time I save, which I do often, I get feedback from the tool on things I might have overlooked etc. One have the possibility to tweak it. There are some of the hints it gives that I disagree with – but it is all over a good way of checking your code.
As a start, if you want to test it, you can copy paste your code into online tools:
JSLint
JSHint
to get a feel of how it works.
Design patterns:
This might be somewhat overwhelming, as there are so many ways (and opinions), but skimming the information and getting a feel on it might be good.
Yes, OO programming is powerful, but as a personal opinion I try not to force JS to be like Java and the like – simulate Classes etc. JS has it's own possibilities, features etc. and when projects get some size the question comes down to design patterns. Sometimes one will encounter an existing code base where one use Class like approach, and then one usually does not have any choice.
You might find this useful. If you do not read it word for word you might find it clarify some of the concept of it:
JavaScript Programming Patterns – Though I strongly disagree with the authors depiction of The Old-School Way; at least in my experience both namespace, re-usability etc. was a concern back then as well. Not for everyone, but not that dark as described.
Learning JavaScript Design Patterns – Might be somewhat big, but still.
Etc. Search the web for “JavaScript design patterns” and the like.

Here's what I got http://jsfiddle.net/xuxcwcsd/5/:
HTML -
<div id="container">
<h1>Testimonials</h1>
<div id="comment"></div>
</div>
CSS -
#container {
border: 2px solid blue;
padding: 3px 10px;
margin-bottom: 20px;
}
h1 {
color: red;
}
p {
text-align: center;
margin-left: 20px;
}
h3 {
color: blue;
text-align: right;
margin-right: 40px;
}
JavaScript -
//create and fill the array
var commt = [ ];
var name = [ ];
var i = 0;
commt[0] = 'comment 1';
commt[1] = 'comment 2';
commt[2] = 'comment 3';
commt[3] = 'comment 4';
name[0] = 'name 1';
name[1] = 'name 2';
name[2] = 'name 3';
name[3] = 'name 4';
//shows how many comments there are
var maxComments = 4;
//get empty elements
var comment = document.getElementById('comment');
//this section will create the inital comment shown
//creates a random number
var number = Math.floor(Math.random() * 4);
//adds the HTML to div with window.onload
window.onload = comment.innerHTML = "<p>" + commt[number] + "</p>" +
"<h3 class='commentSliderH3'>" + name[number] + "</h3>";
//This rotates the comments
setInterval(function () { //same content as above
var number = Math.floor(Math.random() * maxComments);
comment.innerHTML = "<p>" + commt[number] + "</p>" +
"<h3 class='commentSliderH3'>" + name[number] + "</h3>";
}, 1931); // Runs the function every 9031ms

Related

When to use variables? [closed]

Closed. This question is opinion-based. It is not currently accepting answers.
Want to improve this question? Update the question so it can be answered with facts and citations by editing this post.
Closed 6 years ago.
Improve this question
I've started to learn HTML/CSS/JS after several years of no coding at all, previously some simple C++/Python/Pascal stuff.
In one of the tutorials, there is a very simple game to do, comparing a user input with a generated random number and displaying a message if both match.
The question is what is a general practice in web-development:
<p>How many fingers am i holding up?</p>
<input id=userInput type=text>
<input id=guessButton type="button" value=Guess!>
<script type="text/javascript">
document.getElementById("guessButton").onclick=function(){
if (document.getElementById("userInput").value == Math.floor(Math.random()*5)+1)
alert ("You've won");
}
</script>
vs
<script type="text/javascript">
document.getElementById("guessButton").onclick=function(){
var numberGuessed=document.getElementById("userInput").value;
var randomNumber=(Math.random()*5);
randomNumber=Math.floor(randomNumber)+1;
if (numberGuessed==randomNumber)
alert ("You've won");
}
</script>
I get that this example is VERY simple, but when it comes to more complicated logic or nested functions is it better to strive for step-by-step clarity or to avoid the creation of unnecessary variables?
Which is faster?
The answer to this one is it doesn't really matter a whole lot. If it's extremely necessary, for the best speed (both downloading off of the internet and running), if you're only using the values once, you'll want no variables. If you're using the values more than once, you'll probably want to define them in a variable. When downloading, the less data, the better. If you're only using it once, defining it as a variable would technically require more data to be downloaded (i.e. an extra var, an extra semicolon maybe), but it's so insignificant it should not be taken into account most of the time. Your Javascript took less than 1/10th of a millisecond to execute, so this should not be a concern most of the time, either.
Which is preferred?
This is more of an opinion-based question, and therefore, not exactly allowed on Stack Overflow, but I think I can safely say that most developers would say what is important is readability. If this means defining the variables, then so be it. If code cannot be read easily, then it's going to be extremely difficult to expand and modify it, even for yourself, down the road. Readability is especially important when working in a team. Ultimately, though, you should do whatever you prefer.
For speed, as people have stated, the difference is negligible. As for best practice, the second is, in my opinion, demonstrably better.
If someone else is using your code, proper variable naming removes the question of "What are they trying to do?" from the list of problems another developer (or you in a few months) has to solve. Expressive variable names make it so that, If I'm trying to debug a function, I can focus my energy on what's "going wrong", not on what's "going on".
In your second code example, without even looking at how your variables are declared, I can instantly understand what you're trying to do, whether it's working as intended or not. I can then put a debugger before the conditional and check that all the values of the variables you've declared make sense based on what you've named them. For example, I can pretty quickly narrow down what might be wrong if one them is a string, null, NaN, or undefined.
The second example, however, forces me to evaluate what you're doing before I can analyze how you're doing it.
It's a similar philosophy to code comments, really, the smaller the ratio of time spent understanding vs debugging, the more maintainable the code will be.
This is one of those style questions for which you'll likely get a gazillion answers. I would prefer the in-line version unless I was going to use the values more than once. There is probably a tiny difference in performance, since you're having to add names to the local namespace and then (eventually) gc them, but I doubt that difference could be measured in any reasonable use-case.
Yes, you can break down a computation into intermediate variables, and this has the advantage not only of readability, but also of debuggability, since that lets you set breakpoints on each line where something is calculated, and examine the values of the variables.
However, you can also pre-calculate variables. In your case, the DOM element will never change, and so it can be pre-calculated outside the event handler:
const userInputElement = document.getElementById("userInput");
document.getElementById("guessButton").onclick=function() {
var numberGuessed = userInputElement.value;
var randomNumber=(Math.random()*5);
randomNumber=Math.floor(randomNumber)+1;
if (numberGuessed==randomNumber)
alert ("You've won");
};
userInputElement needs to not be executed until the DOM is loaded. So this JS should be either at the end of your body, or wrapped in an event handler such as DOMContentLoaded.
Breaking the calculation of the random number down into two steps is probably going overboard. Most programmers would write this in one line:
var randomNumber = Math.floor(Math.random() * 5) + 1;
In this case, another option is to write this as a little separate function. This has several advantages. First, you would be able to re-use that function in other places in your code. Second, you could test it more easily in isolation. Third, the code where you are using it is simplified.
function getRandomNumber(n) {
return Math.floor(Math.random() * n) + 1;
}
Now you can simplify your event handler to
document.getElementById("guessButton").onclick=function() {
var numberGuessed = userInputElement.value;
var randomNumber = getRandomNumber(5);
if (numberGuessed == randomNumber)
alert ("You've won");
};
However, now that you have both pre-calculated the DOM element, and moved the random number calculation into a function, there is less need to calculate variables one-by-one in your event handler, and you can simplify it to:
document.getElementById("guessButton").onclick = function() {
if (userInputElement.value == getRandomNumber(5))
alert ("You've won");
};
Now you have a very simple, readable event handler, which anyone can look at and easily see what is happening. You also have a separate, re-usable random number generator.
Although not directly related to your question, I would strongly recommend that you indent your code properly, and also adhere to style guidelines for things like the use of spaces.
It is also recommended to use addEventListener instead of assigning to the element's onlick attribute:
document.getElementById("guessButton").addEventListener('click', function() {
if (userInputElement.value == getRandomNumber(5))
alert ("You've won");
});

What is a good example that shows the difference between OOP and procedural programming in JavaScript? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I can't get my head around OOP in JavaScript.
Many years ago, I used to dabble in programming BASIC and learned a bit of COBOL and FORTRAN in school so I am somewhat familiar with procedural programming, but I never learned any of these to a very high level of proficiency or complexity. I've also done a few hackey things with JS but I guess it was mostly procedural in nature rather than OOP.
Recently, I've decided to train myself to become a web developer and learn JavaScript properly, and based on the rave reviews, I decided on Head First JavaScript Programming as my textbook.
The problem I am having is that I can't figure out how or why using objects is really any different or better than using functions and variables. I've looked around at a ton of tutorials and videos but they all say the exact same thing as the book. "Objects are useful because they are analogous to everyday items in real life such as a car. A car has a model year, a make, a weight, a color, etc... A car can also do things such as start, stop, go, etc. They are functions inside the object and called 'methods'." and that is followed by "this is how to create an object:"
var myCar = {
make: "Chevy";
year: 2004;
kilograms: 2000;
color: "blue";
go: function() {
alert("go!");
}
};
Great. Now I know that objects are somehow analogous to real life things and I know how to make one with properties and methods. I get that.
And I can access these property values by calling them as follows:
a = myCar.make;
b = myCar.year;
c = myCar.color;
I can also call the function (or method):
myCar.go();
Wonderful. But I STILL can't figure out WHY I want to do it this way. Why is this better than the following?
myCarMake = "Chevy";
myCarYear = 2004;
myCarKgs = 2000;
myCarColor = "blue";
function go() {
alert("go!");
};
Other than how the code is organized, I don't understand how it's any less procedural. Statements are executed in order, after all. And I don't see what the advantages are to doing all of this.
I keep thinking that what I really need in order to understand this is to see two programs that do the same thing, one coded procedurally with normal variables and functions, and the second one programmed with OO in order to see the difference and how these objects interact with each other in an advantageous way.
I find that all the textbooks and websites that I have found never explain how similar things behave differently or why one is better than the other and there are few if any examples of how to tie it all together well. Most books and tutorials just tell you what you can do but not why you'd want to do that or choose one way over an other. (Irrelevant to this question but another thing I'm wonder about is, I know I can assign a function to a variable but WHY would I want to do that?)
To be clear about what I am looking for, my question is, can someone show me a program that is programmed both ways (both do the same thing and are simple enough for a beginner but complex enough to show why OOP might be needed or advantageous) to highlight the differences and explain why it's better?
In practice, if you have a small script or application, you will not see the difference.
But once you move towards larger applications and bigger code bases, you'll see that OOP works much better than PP.
Here are some high-level advantages of the OOP approach over the PP:
1) Modularity and maintainability
The code becomes modular, the related data and methods are packaged into objects.
This makes it much easier to keep the code under control.
It is complex to see this on few lines of code, but as your code grows, the procedural code most often turns into a mess.
With OOP your code is naturally splitted into smaller parts (objects) and even as the codebase grows, it is still easy to keep the code in order.
The modularity leads to better maintainability - it is easier to modify and maintain the code.
2) Flexibility
It is much easier to replace the part of the code with some different functionality.
For example, you can have the Logger object which writes logs to files. But then you decide to write logs to the database instead.
With PP approach you would need to go over the whole code base searching for something like log_to_file(message, file_name) and replace with something like log_to_db(message, db, table_name).
With OOP you just create the new DbLogger and "plug it" into the system instead of the previous file logger, so the code which logs data will still look the same, like logger->log(message). Even better, you can decide on the type of the logger run-time, for example, read the setting from the configuration file and create whether file logger or db logger.
3) Testability
With OOP it is much easier to take our part of the code (object) and test it alone. If it depends on other objects, these can be replaced with fake implementations (test mocks), so you can really test the piece of code alone.
Just to demonstrate the difference, let's imagine that instead of one car, you now have three (also the go method should really do something with the variables, otherwise it doesn't make much sense):
var myCarMake = "Chevy";
var myCarYear = 2004;
var myCarKgs = 2000;
var myCarColor = "blue";
var yourCarMake = "Ford";
var yourCarYear = 2001;
var yourCarKgs = 1990;
var yourCarColor = "white";
var hisCarMake = "Ferrari";
var hisCarYear = 2011;
var hisCarKgs = 2990;
var hisCarColor = "red";
function go(make, year, kgs, color) {
alert(make + " " + kgs + " " + year + " " color);
};
go(myCarMake, myCarYear, myCarKgs, myCarColor);
go(yourCarMake, yourCarYear, yourCarKgs, myCarColor);
go(hisCarMake, hisCarKgs, hisCarKgs, hisCarColor);
Notice some of the properties of this code:
busness-logic code (the definition of car properties and the go method) is mixed with the client code (the part where we call go), we can not separate them, because client code refers to the global variables we created (like myCarMake)
many repetitions (like CarMake is written 6 times) and it looks messy
easy to make the error (there are errors in last two calls)
hard to maintain - if we add a new parameter for the car, we will have to go over all the code base
Now the version with object (to simplify the code, I keep it as a simple object and separate constructor function, see this for other ways to define the object):
var CarPrototype = { // empty object-prototype
make: "",
year: 0,
kilograms: 0,
color: "",
go: function() {
alert(this.make + " " + this.kgs + " " + this.year + " " this.color);
}
};
// function that constructs the new object
function createCar(make, kgs, year, color) {
var car = Object.create(CarPrototype);
car.make = make;
car.kgs = kgs;
car.year = year;
car.color = color;
return car;
}
var myCar = createCar("Chevy", 2004, 2000, "blue");
var yourCar = createCar("Ford", 2001, 1990, "white");
var hisCar = createCar("Ferrari", 2011, 2990, "red");
myCar.go();
yourCar.go();
hisCar.go();
And some properties of this code:
the business logic is clearly defined and separated from the client code, client code is not aware of internal structure of the car object
less repetitions and in general the code looks clearer
once the object is defined, it is really complex to make the error (you just do myCar->go(), no parameters passing, no chance to mix them or pass in the wrong order
easier to modify (if we add a new property for the car, the myCar.go() calls in client code don't need to be changed)
For sure, I didn't mention all the reasons to use OOP over PP, but I know this from practice - try to spend some time learning OOP principles and start using it and you'll see the huge improvement in code structure. You will make mistakes and do things wrong in the beginning, but the result will anyway be better than procedural code.
The general approach here is more important than specific language constructs, you can use same principles in C (which is not an OOP language) and in javascript (which has a specific OOP support) as well as in other languages.
I don't know a resource which compares PP and OOP side by side, but I think you don't really need it. Just look at examples of OOP applications and imagine how these would look like if written in procedural style.
My favorite book about OOP is Design Patterns, it demonstrates how elegant and powerful can be interaction between objects.
Probably, you will also need to find something where basic OOP concepts are explained (already mentioned encapsulation, polymorphism, inheritance) and principles (most notably SOLID).
Truthfully, I always found the idea of properly scoped variables a good argument for the OOP approach of javascript.
Taking your example for instance:
var myCar = {
make: "Chevy",
year: 2004,
};
var make = "Ford";
console.log(make);
console.log(myCar.make);
Yields "Ford", then "Chevy". The reason scoping can be an issue within JS is the sheer number of libraries that can be pulled in. Yes small programs tend to be easier to write using procedural. But when you are pulling in a dozen other libraries, you do not know which approach they use for declaring variables - which can lead to obscure errors.
Yes, you could just declare the variables within the function definition and they would then be scoped to just that function (example below), but then they can't easily be reused!
function go(){
var make = "chevy";
console.log(make);
};
go();
console.log(make) ///throws undefined 'error'
OOP provides an approach that is scope safe, and easy to reuse (which is great for external libraries).
They say OOP is about inheritance, polymorphism and encapsulation.
We will leave encapsulation aside, as it has nothing to do with OOP, but rather with modules. (At last, modules are the part of the language!)
Inheritance is a powerful concept that makes possible to reuse both logic and data. Extending your car example, we can do the following.
var AbstractCar = {
go: function () {
alert('go ' + this.make+ '!');
}
};
var MyCar = Object.create(AbstractCar, {
make: { value: 'Chevy', writable: true }
});
var YourCar = Object.create(AbstractCar, {
make: { value: 'Mustang', writable: true }
});
MyCar.go(); // go Chevy!
YourCar.go() // go Mustang!
Polymorphism, on the other hand, allows you to treat different kinds of objects as one, as long as they conforms to the interface. Or, in the other words, as long as they can do want we want them to do.
For example, we need a string representation for out objects. Anything, that has a toString method could be concatenated with a string.
var myCar = {
make: "Chevy",
year: 2004,
toString: function () {
return this.make + ' ' + this.year;
}
};
var statement = 'I want to sell ' + myCar;
console.log(statement); // I want to sell Chevy 2004
And that's really it.
OOP is not some superior technique that should be mastered for what its worth. Though it can pretty handy. : )

Javascript - is there any hard limit (or performance impact) for namespace nesting?

I'm trying to learn a bit more about Javascript apart from the typical var x = function(){...} constructs, so I gone for namespaces.
In PHP, I always work with namespaces to avoid collisions and to organize my constants, classes and functions. So far, I've just done the basic namespacing like this:
var helpers = {
strings: {
add: function(a, b) {
alert(a + ' plus ' + b + ' equals to ' + (a + b));
},
msgbox: function(text) {
alert(text);
}
}
}
So I can write HTML blocks like this:
<button class="ui-button" type="button" onclick="helpers.strings.msgbox('Hello, world!');"><img src="assets/images/alert.png" alt="Alert"> Click me!</button>
My questions are:
is there any practical/hard limit to the number of levels I can nest my namespaces within?
is there any performance impact associated with the level of nesting for any given function?
can I extend a given namespace later in time? Like... having a core.js file and extending the strings namespace for adding more functions in, let's say, extended.js?
I'm not going to build a horribly nested structure or anything like that but I would just like to know if there are any practical limitations imposed by the browser engine or the language itself, so my question is more of a theorical nature (I'm not building a construct to test this, in this case).
is there any practical/hard limit to the number of levels I can nest
my namespaces within?
Obviously there is because if nothing else more levels will require more memory and memory is finite, and in practice there other restrictions will also be in place (derived from the implementation details of each particular JavaScript engine).
But the practical answer is: if you have reason to believe you might go near these limits, you are doing something wrong.
is there any performance impact associated with the level of nesting
for any given function?
Yes, because each level of indirection involves finding where the next nested "namespace" object is in memory and looking up its properties. In practice this cost is infinitesimal compared to other stuff that your code will be doing, so you will not be able to measure any difference unless the number of levels is large and you are digging up a nested value within a loop.
For example, this is not the best of ideas:
for(var i = 0; i < 1000000000; ++i) {
ns1.ns2.ns3.ns4.ns5.ns6.ns7.ns8.ns9.ns10.ns11.ns12.ns13.count += 1;
}
Fortunately if you ever need to do this there is a simple workaround:
var ns13 = ns1.ns2.ns3.ns4.ns5.ns6.ns7.ns8.ns9.ns10.ns11.ns12.ns13;
for(var i = 0; i < 1000000000; ++i) {
ns13.count += 1;
}
can I extend a given namespace later in time? Like... having a core.js
file and extending the strings namespace for adding more functions in,
let's say, extended.js?
You can, but you have to be careful so that both of these files use a mechanism for injecting variables into a namespace that does not actually replace the contents of the namespace.
There is a slight performance hit for each level of nesting, as it's another lookup. And there's the additional overhead of downloading more code if this is for client-side scripting. The first is likely quite minor. The second you'll have to decide for yourself.
And you can easily add new functions to your namespaces later:
helpers.strings.multiply = function(a, b) { /* ... 8/}
Although I made heavy use of namespacing for years, I rarely do so now, preferring a module loading system to manage my dependencies, and not exposing even something like helper. But these sorts of namespaces are easy to create and easy to use if you choose to do so.

Why is there a need for javascript coding conventions?

Suppose I have to write a javascript function:
function(){
var a=1;
var sum=1;
for(var i=0;i<6;i++){
sum=sum+a+1;
}
console.log(sum);
}
Someone recommended me to write this function like this:
function () {
var a = 1;
var sum = 1;
for (var i = 0; i < 6; i++) {
var sum = sum + a +1;
}
console.log(sum);
}
With more blank space, I know this rule, but I don't how it works, or what can I benefit from it?
It is a matter of opinion what good style is, but in a general sense picking some style and consistently following it throughout your code makes it easier to read (both for other people and for you when you come back to it later).
In my experience most people find code easier to read with the extra spaces as shown in your second example.
I don't like putting a space between function and (). Or, where there is a function name I don't put a space between the name and the parentheses: function someName().
Note also that with modern code editors that have syntax highlighting (like Stack Overflow does) it is much easier than it used to be to read code that doesn't have spaces. Compare the following two:
for(var i=0;i<6;i++)
for(var i=0;i<6;i++)
Reading and editing the latter, all in black and white, really annoys me, but I don't mind the coloured version anywhere near as much. I still prefer it with the extra spaces though.
I'd make some other changes in your function:
function() {
var a = 1,
sum = 1,
i;
for(i = 0; i < 6; i++){
sum += a + 1;
}
console.log(sum);
}
The benefit of coding style is enhanced readability. It does not really matter what style you decide to stick to, as long as you DO stick with a uniform style, and can agree with your coworkers on its readability, which is not always easy.
These coding conventions are for humans, they increase readability. Suppose I have written an expression like this:
x=(a*b/2)+m-n+c*(d/e);
It looks clumsy and difficult to read. It would have been easier to understand if we had used spaces around operators like this:
x = (a * b / 2) + m - n + c * (d / e);
Again using blank line increases readability by denoting sections. For example:
function foo() {
var a;
var b;
// a blank line here to specify the end of variable declarations
if (some_cond) {
} else if (another_cond) {
}
// another blank line to specify end of some logic
//more codes here;
}
If you do not follow these guidelines and all team members do not agree in some convention then it will be very difficult to maintain a big project for long time.
Finally note that, the conventions are not for compilers, they are for humans. That's why it is called coding guidelines, not language syntax.
May be you should read more about javascript closure, and you can follow "Google Javascript Style Guide".
Following some uniform style guidelines when coding makes code easier to read and helps you writing beautiful code, and others understanding (and loving!) your code.
For sure there are loads of resources on the net (just by googling for a while you get some javascript guides or guidelines), but this one is quite easy, simple and complete:
http://javascript.crockford.com/code.html
It's not a rule. It's just coding convention style. You don't need to follow if you don't want. But this style can make your code more readable, easier to maintain, and cleaner. To me, I prefer to have space rather than narrow letters. Again, it's not a rule.
Coding style is always very personal; one person likes condensed code so that they can see as much as possible on one screen, another needs the opening and closing braces on a separate line, etc.
When only coding for yourself, you should choose whatever is best for you. But when you start working in teams and others have to maintain your code and visa versa, it becomes important to agree on one coding style ... and this can be hard.
I've sat in coding style discussions and they're very uncomfortable, because you're giving up some of your personal preferences albeit for the greater good. After a brief moment of discomfort you will get used to it ;-)
The second version isn't equivalent to the first, as it declares an inner 'sum' variable, unless Javascript doesn't do what it says on the tin with that.
The extra blank lines don't contribute anything much IMHO, but I probably wouldn't die in a ditch about them. However an equally valid concern is download speed, which is made worse by the suggestion.

Implementing a complicated decision table in JavaScript

Here's an implementation details question for JavaScript gurus.
I have a UI with a number of fields in which the values of the fields depend in a complicated fashion on the values of seven bits of inputs. Exactly what should be displayed for any one of the possible 128 values that is changing regularly as users see more of the application?
Right now, I've for this being implemented as a decision tree through an if-then-else comb, but it's brittle under the requirements changes and sort of hard to get right.
One implementation approach I've thought about is to make an array of values from 0x0 to 0x7F and then store a closure at each location --
var tbl; // initialize it with the values
...
tbl[0x42] = function (){ doAThing(); doAnotherThing(); }
and then invoke them with
tbl[bitsIn]();
This, at least makes the decision logic into a bunch of assignments.
Question: is there a better way?
(Update: holy crap, how'd that line about 'ajax iphone tags' get in there? No wonder it was a little puzzling.)
Update
So what happened? Basically I took a fourth option, although similar to the one I've checked. The logic was sufficiently complex that I finally built a Python program to generate a truth table in the server (generating Groovy code, in fact, the host is a Grails application) and move the decision logic into the server completely. Now the JavaScript side simply interprets a JSON object that contains the values for the various fields.
Eventually, this will probably go through one more iteration, and become data in a database table, indexed by the vector of bits.
The table driven part certainly came out to be the way to go; there have already been a half dozen new changes in the specific requirements for display.
I see two options...
Common to both solutions are the following named functions:
function aThing() {}
function anotherThing() {}
function aThirdThing() {}
The switch way
function exec(bits) {
switch(bits) {
case 0x00: aThing(); anotherThing(); break;
case 0x01: aThing(); anotherThing(); aThirdThing(); break;
case 0x02: aThing(); aThirdThing(); break;
case 0x03: anotherThing(); aThirdThing(); break;
...
case 0x42: aThirdThing(); break;
...
case 0x7f: ... break;
default: throw 'There is only 128 options :P';
}
}
The map way
function exec(bits) {
var actions = map[bits];
for(var i=0, action; action=actions[i]; i++)
action();
}
var map = {
0x00: [aThing, anotherThing],
0x01: [aThing, anotherThing, aThirdThing],
0x02: [aThing, aThirdThing],
0x03: [anotherThing, aThirdThing],
...
0x42: [aThirdThing],
...
};
in both cases you'd call
exec(0x42);
Since the situation (as you have described) is so irregular, there doesn't seem to be a better way. Although, I can suggest an improvement to your jump table. You mentioned that you have errors and duplicates. So instead of explicitly assigning them to a closure, you can assign them to named functions so that you don't have to duplicate the explicit closure.
var doAThingAndAnother = function (){ doAThing(); doAnotherThing(); }
var tbl; // initialize it with the values
...
tbl[0x42] = doAThingAndAnother;
tbl[0x43] = doAThingAndAnother;
Not that much of an improvement, but it's the only thing I could think of! You seem to have covered most of the other issues. Since it looks like the requirements change so much, I think you might have to forgo elegance and have a design that is not as elegant, but is still easy to change.
Have you considered generating your decision tree on the server rather than writing it by hand? Use whatever representation is clean, easy to work with, and modify and then compile that to ugly yet efficient javascript for the client side.
A decision tree is fairly easy to represent as data and it is easy to understand and work with as a traditional tree data structure. You can store said tree in whatever form makes sense for you. Validating and modifying it as data should also be straight forward.
Then, when you need to use the decision tree, just compile/serialize it to JavaScript as a big if-the-else, switch, or hash mess. This should also be fairly straight forward and probably a lot easier than trying to maintain a switch with a couple hundred elements.
I've got a rough example of a JavaScript decision tree tool if you want to take a look:
http://jsfiddle.net/danw/h8CFe/

Categories

Resources