What is the purpose of this CanvasJS code line? [closed] - javascript

Closed. This question needs details or clarity. It is not currently accepting answers.
Want to improve this question? Add details and clarify the problem by editing this post.
Closed 5 years ago.
Improve this question
I am using CanvasJS and always used these lines here:
var chart = new CanvasJS.Chart("chartContainer",
{
...
});
chart.render();
Unfortunately, I do not know what these lines are doing. Can someone explain it to me? Thank you very much!

What are these lines doing??
Well on their own not much. In the context of a javascript engine a lot or not much.
The short version.
Creates and renders a CanvasJS.Chart, putting the chart in the DOM element identified as "chartContainer". Well it would if it was complete.
The long version.
var is a javascript token. It is used to declare a variable and is usually followed by the name or variable identifier of the variable. In this case chart. You could also use the tokens let, const, or function (and some others) which have different scope and access to the contents of the variable they declare
= is an assignment operator. It moves the data from the expression on the right to the variable/property on the left.
new (javascript token)is a special token that modifies the way a function is called (In days of old when javascript was still considered a toy it was used to make javascript look hip and cool) It is rather superfulouse in the language so you can ignore it for now.
CanvasJS (variable identifier) is a variable that was declared somewhere in the javascript code (hopefully) using one of the declaration tokens (most likely function). It has been capitalised which is significant. In Javascript when you capitalise a variable identifier you are telling the world that this is a special function that will always return an Object if called. It also tells you that it might have a special property called prototype which helps the javascript engine run your code a little quicker and helps you by simplifying your data structures using something called inheritance.
.Chart (property identifier) This is a property, the dot "." between CanvasJS and Chart signifies property of (called Dot notation, but could equally have been the not so popular, Bracket notation CanvasJS["Chart"] same as CanvasJs.Chart. )
So Chart is a property of CanvasJS. A property is like a variable but rather than being alone the property is attached to an Object. This is very handy for grouping related data and information
Because CanvasJS has a big C, Chart is most likely (but not a certainty) one of the special prototype properties of CanvasJS.
( Opening brace. When you see one of these after a variable identifier it means that the variable is a function that can be called. It at some point must have a closing brace ) What is between ( and ) are called function parameters, or arguments and are passed to the function. There is a whole set of rules governing what goes between the ( and ) and way to much to cover now.
Calling a function does a lot of special stuff, in the most basic terms the javascript engine locates that code that belongs to the function, packs its bags with arguments, goes to the function code, sets up camp, executes the function code and then returns with all the groover holiday shots. Anyways I digress
"chartContainer" first argument, a string literal. It is abstractly a devoted bit of memory that holds a "string" of characters. Strings and string literals have many uses, but looking at the content of this string I can guess what it is used for.
It is an identifier, name, or query used to find a DOM object (Document Object Model, the ugly bit hanging of the side of javascript, the dude whose party Javascript came to but nobody likes and wishes would go away) The bit of HTML that will hold the chart
, comma used to separate arguments (in this case)
{ Opening curly or Object literal. Like the string literal but instead of characters it contains properties. needs to have a closing curly at some point
... the dots by themselves in this context is just gibberish and will cause the javascript parser to stop dead in its tracks and not look at anymore code. We know it's gibberish, so does javascript, but rules are rules so we need to clean this up.
//... commented epsilon referring to the missing code.
} closing object literal.
) end of function's argument list.
; End of expression, like new it is not really needed but god (AKA Douglas Crockford) linted that it must be so, or you will be smittened by the obscure bugs and the taunts of JSLint and friend forever. (also you can not see return characters, so ; tells you this statement/expression/blockless code block, is complete.)
At this point javascript will call the function CanvasJs.Chart passing the arguments, a string and an object. The function will do its thing and with luck will return a object (we know it will be an object because the new token and that Chart has a big C). The = will give the variable identified as chart (note the small c) a referance to the returned object.
chart.render() Property of referenced object held by chart called render is a function, call it with no arguments. I am guessing that it draws a chart and that chart can be seen in the DOM inside an element that may have the id chartContainer.

Related

What's the difference between str.fun() / str.fun / fun(str) in JavaScript?

I tried googling but couldn't find a precise answer, so allow me to try and ask here. If the question does not seem proper, please let me know and I'll delete it.
In JS you've got three different way of writing certain build in functionalities:
str.length
str.toString()
parseInt(str)
I wonder if there is a reason behind these different ways of writing. As a new user I don't grasp why it couldn't be streamlined as: length(str) / toString(str) / parseInt(str) or with dot formulation.
I however think if I do know the reason behind these differences, it would give me a better understanding of JavaScript.
Length is one of the attributes of string in JavaScript. Hence you use string.length to get the length of the string.
toString is a function for string objects, hence we use stringobj.toString().
parsInt(str) is a global function which takes string as a parameter.
JavaScript is object-oriented, so there are functions or procedures which require first an object to use as this in their bodies. str.length is a property, both syntactically and semantically. It doesn't require any parameters and represents some quality of the object. obj.toString() is a method (a function attached to an object), which doesn't represent any characteristics of the object, but rather operates on its state, computes some new values, or changes the state of the object a lot. parseInt(str) is a "global" function, which represents an operation not attached to any type or object.
Under the hood, these three ways may be well implemented with just calling a function, passing this as the first parameter (like C# does, for example). The semantic difference is the important one.
So why not use just the third syntax, like for example PHP does? First, it doesn't bloat the global environment with lots of functions which only work for one specific case and type, allowing you to specify any new function you want without breaking the old functionality. Second, it ecourages you to use object-oriented concepts, because you can already see working objects and methods in the language, and can try to make something similar.
And why isn't parseInt a method? It can as well be str.toInt() without any issues, it's just the way JavaScript designers wanted it to be, although it seems also a bit logical to me to make it a static method Number.parseInt(str), because the behaviour of the function is relevant more to the Number type than the String type.
JavaScript is based around objects. Objects have properties (e.g. a User object may have name and age properties). These are what define the user and are related to the user. Properties are accessed via dot-notation or brackets notation (to access Eliott’s age, we’ll use either eliott.age or eliott['age'] — these are equivalent).
These properties can be of any type — String, Number, Object, you name it — even functions. Now the proper syntax to call a function in JS is to put round brackets: eliott.sayHello(). This snippet actually fetches Eliott’s sayHello property, and calls it right away.
You can see Eliott as a box of properties, some of which can be functions. They only exist within the box and have no meaning out of the box: what would age be? Whose age? Who’s saying hello?
Now some functions are defined at the global level: parseInt or isNaN for instance. These functions actually belong to the global box, named window (because legacy). You can also call them like that: window.parseInt(a, 10) or window.isNaN(a). Omitting window is allowed for brevity.
var eliott = {
name: 'Eliott',
age: 32,
sayHello: function () { console.log('Hello, I’m Eliott'); }
};
eliott.name; // access the `name` property
eliott.age; // access the `age` property
eliott.sayHello; // access the `sayHello` property
eliott.sayHello(); // access the `sayHello` property and calls the function
sayHello(eliott); // Reference error: `window.sayHello` is undefined!
Note: Some types (String, Number, Boolean, etc.) are not real objects but do have properties. That’s how you can fetch the length of a string ("hello".length) and reword stuff ("hello, Eliott".replace("Eliott", "Henry")).
Behaviour of these expressions is defined in ECMAScript grammar. You could read the specification to understand it thoroughly: ECMAScript2015 specification. However, as pointed out by Bergi, it's probably not the best resource for beginners because it doesn't explain anything, it just states how things are. Moreover I think it might be too difficult for you to be able to grasp concepts described in this specification because of the very formal language used.
Therefore I recommend to start with something way simpler, such as a very basic introduction to JavaScript: JavaScript Basics on MDN. MDN is a great resource.
But to answer your question just briefly:
str.length is accessing a property of the str object.
parseInt(str) is a function call
str.toString() is a call of a function which is a property of the str object. Such functions are usually named methods.
Functions and methods are in fact very similar but one of the differences (except for the obvious syntax difference) is that methods by default have context (this) set to refer to the object which they're part of. In this case inside of toString function this equals to str.
Note: Accessing a property (as in str.length) could in effect call a getter function but it depends on how the object is defined, and is in fact transparent for the user.

Classless object in shorthand notation

So, I dived head first in Marijn Haverbeke's Eloquent Javascript and swam directly to the Electronic Life chapter.
There we observe the spontaneous generation of an object :
{"#": Wall,"o": BouncingCritter}
Wall and BouncingCritter are defined elsewere :
function Wall() {}
function BouncingCritter() {
this.direction = randomElement(directionNames);
this.name = word();
};
BouncingCritter.prototype.act = function(view) {
if (view.look(this.direction) != " ")
this.direction = view.find(" ") || "s";
return {type: "move", direction: this.direction};
};
BouncingCritter.prototype.toString=function(){
return this.name +"\t"+ this.direction;
}
---> I don't get what sorcery is happening there.
Well, I see we're creating an object on the fly, and since it's going to be used only once, no need to define a class. OK.
I understand that hitherto this anonymous object has two properties, which are themselves classes, that will be instantiated several times down the road. I'm starting to flutter but I'll get along. One of those (Wall) is quite empty, which will later prove useful as "nothing" is somewhat better than 'undefined'. Fine.
What I don't get is the use of string constants "#" and "o" on the left hand side of the colon. Could someone please expand on this ?
Heartly thanking,
What I don't get is the use of string constants "#" and "o" on the left hand side of the colon. Could someone please expand on this ?
The property has to be called something. Those are just rather unhelpful names which tell you nothing about what the property actually holds.
… until you look at the context. From the link you provided:
The “#” characters in this plan represent walls and rocks, and the “o” characters represent critters.
It's using # as the name for the wall property because that is the symbol used to render it in the UI. Ditto "o"/citter.
(That still isn't a great name though: It tightly couples the internal name to the presentation of it, which would start to fall apart if the UI was later changed to use (for example) pretty graphics instead of ASCII art)
In this scenario it's more like a dictionnary. It just use to say that the character # or o represent respectivly the class Wall and BouncingCritter.
Edit (after reading your book as fast as i could): When he instanciate the World(map, legend), legend is the dictionnary. Later in the code he creates the grid and for every characters from the string representation of the world, he instanciates the correct class according to the legend dictionnary he gave var element = new legend[ch]();.
OK folks, thanks for your answers. I dug a bit further and came across a very clear and concise (nifty, indeed) explanation as to the ways of the object literal notation : Nifty Javascript - Objects.
What confused me most at first in
{"#": Wall,"o": BouncingCritter}
are the quotes surrounding properties names, and the fact that "#" would otherwise be an illegal character for a property name.
To wrap my head around this, I had to write it down, and I share below, for what it's worth.
The "legend" is anonymous classless object defined, when we construct the World,
by the block {"#": Wall,"o": BouncingCritter}
Says Marjin :
A legend is an object that tells us what each character
in the map means. It contains a constructor for every
character—except for the space character, which always
refers to null, the value we’ll use to represent empty
space.
In the World constructor, we populate the grid.space array according to what we
read from the 'map' (which is instantiated by the array 'plan').
The character read from the map (either 'o' or '#') serves as the key in the
hashtable (a.k.a "object") 'legend'. The corresponding value is a class (either
'Wall' or 'BouncingCritter') which is then instanciated. The resulting object is
finally stored in the grid.space array.
Note that the original literal notation {"#": Wall,"o": BouncingCritter} for
creation and the subsequent employ of square brackets in the function
'elementFromChar'
var element = new legend[ch]();
allows for the use of the
otherwise illegal character '#' as the name of the property.
Here be rant :
Needless to say, I'm not very happy with all this. I guess it's the kind of stunt that gives javascript a bad reputation sometimes. All in all, I'm starting to consider that the title of the book, "Eloquent Javascript", may be a little overstated or even plain misleading.
Granted, it is an impressive demonstration of object-fu maestria, but neither the code nor the text are specially clear. I had a very hard time stitching the code patches together and getting the project to work and I feel that the object breakdown used to model the problem is overly complicated. But heck, I'm learning, so my opinion is completely unauthorized ;-)
end-of-rant

How many globals make sense to be passed to the IIFE wrapper?

To which extent does it make sense to pass plenty of global values to an IIFE?
The common thing is just to pass 3 as far as I see everywhere (window, document and undefined).
But... would it make sense to pass more if they are used more than 10 times in the code just for the fact of minification?
In my case I found the global variable Math 14 times in the code. It would make sense to pass it to an IIFE in order to save 42 bytes. Which in this case is not a lot, but if we sum bit by bit different global variables, then it would always make sense to pass as many global variables as possible, right? (Symbol, Object, Error, Date, JSON...)
(function($, window, document, Math, undefined) {
$.fn.mydemo = function() {
};
}(jQuery, window, document, Math));
Then, why isn't this a common approach?
Update:
To explain the 42 bytes of reduction:
Math = 4 characteres
1 character = 1 byte
14 times Math = 56 bytes
Math will get replaced by a single character after minification
As the function can be defined as function($, w, d, m, u)
14 characters of the shorten word Math (m) = 14 bytes
56 - 14 = 42 bytes of reduction
First of all, those values are not IIFEs.
And this is not about “saving characters” by having shorter variables names inside the function (at least not mainly), but rather about variable lookup and the “cost” associated with it.
If you were to use f.e. document inside your function without passing it in, then first a variable named document would be searched in the scope of the function, and only when that fails, search would continue in the scope above that, and so on.
That is the reason for passing such objects as parameters into the function – so that a direct reference to them within the function scope exists, and they do not have to be looked up in higher outside scopes.
Sometimes, you might even see this used in such a form like this:
(function(document) {
// do something with document, such as:
document.foo();
document.bar = "baz";
})(document);
– in that form, it should be even more clear that this is not about saving characters in variable names. The object is still referred to as document inside the function (which makes it clear what it is supposed to represent – the global document object), and the only effect achieved by this is said shorter lookup.
There are a number of cases where it makes sense to pass variables to an IIFE.
Aliasing
Passing a variable to an IIFE allows you to rename the variable within the function. This is commonly seen when using jQuery, particularly when noConflict is used:
(function ($) {
//in here $ will be the same as jQuery
}(jQuery));
Aliasing also helps minifiers to minify code, when you see something like:
(function (document, slice, Math) {
...
}(document, Array.prototype.slice, Math));
The minifier can rename the parameters to whatever it wants, and save you bytes. For large scripts using these properties a lot, it can be significant savings when it gets turned into:
(function(a,b,c){...}(document,Array.prototype.slice,Math));
Portability
This is more of an edge case than a general rule, but it's common to see a global IIF in the form of:
(function (global /* or window */) {
...
}(this));
This allows for portability between node.js and the browser so that the global variable has the same name in both environments.
Character Savings
While I already mentioned that minifiers can reduce the character count by changing the names of aliases, you may want to do this manually if you're participating in a code golf challenge.
Reference Safety
If you're authoring a script that must work in whatever environment its dumped into (think google analytics), you'll want to be sure that the global methods you're calling are what you expect. Storing a reference to those functions by passing them as parameters is one way to preserve the reference to the functions from becoming overridden by a malicious or ignorant programmer.
To answer the question in your title:
How many globals make sense to be passed to the IIFE wrapper?
As many as you need and no more. If you need to alias one or two variables, pass one or two references. If you need to be sure that the global functions aren't being changed, you may end up with 100 parameters. There's no hard-and-fast rule on this.
would it make sense to pass more if they are used more than 10 times in the code just for the fact of minification?
If you care that much about minification, sure, why not?
The common thing is just to pass 3 as far as I see everywhere (window, document and undefined)
Yes, altough you see not passing document, or passing jQuery (aliased as $), just as often. And of course it's not only about minification, but about performance, and you only care for window and document on that behalf.
it would always make sense to pass as many global variables as possible, right?
Well, except you don't use them in your code. Symbol, Object, Error, Date, JSON, Math and the others are not needed that often in most code. And developers don't like to do those byte counts you are suggesting every time they change a bit of code, so this IEFE boilerplate just stays as it is (and imho there's much cargo cult to it).
You would let your minifier do this automatically if you'd really care.

Strategy for handling case sensitivity of javascript properties

I'm sure someone is going to shout at me for asking this question, but here goes: in Javascript, what is the best strategy for coping with the fact that the properties of objects are case-sensitive? If I create an object with a property called FavouriteDrink, but then I later start referring to it as favouriteDrink then I could end up in a mess.
I don't want a big library here, but is there any way to define the object so that FavouriteDrink is defined somewhere, and where in Visual Studio 2012 some intellisense will help me choose the correct property name if I can somehow contextualise the object I'm dealing with? It is only properties I'm pondering here.
Thanks.
It doesn't work this way
if i look at your your code and see :
FavouriteDrink() {}
the first thing will popup in my mind is this is a constructor function not just a normal function
and by looking at this following one
favouriteDrink() {}
i would tell that this is a normal function and i can't use it as a constructor - can't be called with new
Here is some other examples
first_name // variable
FIRST_NAME // uppercase variables shouldn't change
_first_name // local variable not intended to be used out of its scope
var FIRSTNAME = {} // name space
it’s a good idea to follow a convention as to how the words will be separated
see this Code Conventions for the JavaScript Programming Language
For the other part of your question i'm using VS 2012 and i installed JSEnhancements
and i can see all my object element
JavaScript shares the following conventions with Java and ActionScript 3.
ALL_UPPERCASE
Use this as the variable name when you define a constant, or a value that should never change.
For example, myObject.NUM_TIMES_CLICKED = 2 would be a poor candidate for a constant because it is likely to change. However, myObject.APPLE_FRENCH_SPELLING = 'pomme' would be appropriate here.
firstWordLowercaseAndTheRestAllUppercase
Use this when you are defining anything that is not a constant or a class. You would use this for most things, for example, myObject.numTimesClicked, myObject.myFunction(), myObject.returnString.
AllWordsCapitalized
Use this when you are defining a function that defines a "class," generally any function you would call with the syntax myObject.myClassInstance = new MyClass(). Notice how myClassInstance is in camel-case because it is an instance of the class. However, MyClass is all caps because it is meant to be invoked with new.
You would define the class initially like this: myObject.MyClass = function(){};
WebStorm and Sublime Text are great tools that offer the code intelligence you're looking for.
WebStorm does this out of the box, but my personal preference is Sublime Text with the SublimeCodeIntel plugin.
That being said, it's probably best for you to be using naming conventions:
UpperCamelCase is for classes
ALL_CAPS_SNAKE_CASE is for constants
lowerCamelCase is used for everything else

correct function parameters designation

Every time i pass some parameters to a JavasScript or jQuery functon, i use some random letters. What are the correct letters for the corresponding variable types?
function(o){} for example is for a object. But what are the other letters? Do someone have a list of those?
I advise you not to assign names according to types but according to the data that the variable contain. If you pass an object that contains the configuration for a function call the variable configuration if you pass a variable that contains a name call it name and so on. In this way the code is more readable and understandable.
Any letter will do, there is no such thing as a standard for using letters as parameters.
However, using letters for parameters is bad practise, because a letter does not describe what the parameter is intended for.
Consider this example:
function ShowBusyCursor(s) {
//...
}
If you look at the function header, you cannot guess what the parameter s stands for. But if you change the code to this:
function ShowBusyCursor(cursorIsDisplayed) {
//...
}
The parameter cursorIsDisplayed is a lot more developer-friendly and tells you it's a boolean that can be set to true to display the cursor. If you used s, you would have to look into the code to figure that out.
Here is a good list of letters I could think of:
o - object
a - array
s - string
d - date
n - number
r - regexp
b - boolean
But seriously, jokes apart, I think you might be mixing up the packed/minified source with the actual source that developers write. For example, this little function looked like this originally:
function myFunction(personName) {
this.name = personName;
}
But after minifying, it becomes:
function myFunction(a){this.name=a}
packer is one such utility by Dean Edwards that will minify your Javascript. Play with your source code at this website and see the compressed output. Check the Shrink variables option on the right to see how parameters and other variables get renamed.
This however shouldn't affect how you write your code at all. Be it Javascript, or any other language, all identifiers - variables, function names, class names, etc. should be named after what they represent or do rather than obscure shorthands.
Re-iterating what mck89 said, it's better to go with explanatory variable names rather than just a letter for the type. What if you have more than one parameter of the same time, do you start appending numbers?
I have often seen explanatory variable names which include the type, for instance sFirstName would be a string denoted by the "s", bForce would be a boolean, oConfig would be an object and nSubTotal would be a number.
This is a variation of Hungarian notation, and I'd advise against using single-letter variable names. What if you need to pass in 2 of any one data type? Like others have said, it also doesn't represent the meaning of the variable very well. I think this is much better:
function foo(sFirstName, sLastName)
{
alert("Hi, my name is " + sFirstName + " " + sLastName);
}

Categories