When should I put a semicolon after a function in javascript? - javascript

My examples:
(First example area is the function assignment with semicolon)
function makeImage() {
var canvas = document.getElementById("tshirtCanvas");
**canvas.onclick = function () {
window.location = canvas.toDataURL('image/png');
};**
}
vs
window.onload = function() {
var button = document.getElementById("previewButton");
button.onclick = previewHandler;
makeImage();
}
I thought I had the hang of when to use it, and when not to, but I guess I do not. Thanks.

You should put a semi-colon after a function when you use it as a value:
var fn = function () {};
blarg.fn = function () {};
doStuffWith(function () {});
If you're just declaring a named function by itself, you don't need the semicolon:
function doFoo() {}
Note that in the top cases, you don't always have to have a semicolon, but you should put one anyway.

Function expressions get semicolons (normal line ending rules apply). Function declarations do not.
http://javascriptweblog.wordpress.com/2010/07/06/function-declarations-vs-function-expressions/

Your function declaration doesn't need it after. Just if you are calling it.
function doThis(args){
getterMethod(args);
}

If you are assigning a function to a property, you should put a semicolon.
So you could put a semicolon for the window.onload because you are assigning a function to the onload property of the window. The semicolon isn't required, but I highly recommended you put it to prevent confusion.
window.onload = function() {
init();
doSomethingElse();
};
From the MDN Docs.

Related

why won't the arrow function work here in javaScript when trying to get an onclick event

Why does the arrow function not work when defining a function in javascript?
This works, but the arrow function doesn't for some reason.
function changeImage() {
document.getElementById('header').innerHTML="<img src='open.jpg' height='200px'/>";
}
This is the example that does not work:
let changeImage = () => {
document.getElementById('header').innerHTML="<img src='open.jpg' height='200px'/>";
}
file.js
let clickOpt =
document.getElementById('header');
clickOpt.onclick= changeImage;
let changeImage = () => {
document.getElementById('header').innerHTML="<img src='open.jpg' height='200px'/>";
}
function declarations are hoisted to the top of the enclosing scope; let declarations are not (well not completely). You'll see an error in your browser console that will go away if you do the onclick assignment after the let declaration.
let changeImage = () => {
document.getElementById('header').innerHTML="<img src='open.jpg' height='200px'/>";
}
clickOpt.onclick= changeImage;
By contrast, a function declaration is treated as if it actually appeared at the very start of its containing function or <script> body.
Note that there's no really good reason to use a => function in this case.

Make a function run once by redefining

I've found myself using this pattern recently to do initialization that should only ever run once:
function myInit() {
// do some initialization routines
myInit = function () {return;};
}
This way if I had two different methods which required something myInit did, it would ensure that it would only run once. See:
function optionA() { myInit(); doA(); }
function optionB() { myInit(); doB(); }
In the back of my head I feel like I'm missing something and I shouldn't be doing this. Is there any reasons why I shouldn't write code like this?
Is there any reasons why I shouldn't write code like this?
One reason is that the function will only work as you intend in the scope it was defined in. E.g. if you pass the function somewhere else, it won't be affected by your modifications and in the worst case would create an implicit global variable. E.g.
function myInit() {
// do some initialization routines
myInit = function () {return;};
}
function foo(init) {
init();
init();
}
foo(myInit);
The better approach is to encapsulate the whole logic:
var myInit = (function() {
var initialized = false;
return function() {
if (initialized) return;
initialized = true;
// do some initialization routines
};
}());
Now, no matter how, where and when you call myInit, it will do the initialization step only once.
May be you can do something like,
var myInitCalled = false; // Global declaration of flag variable
function myInit() {
// do some initialization routines
myInitCalled = true; // Setting the global variable as true if the method is executed
myInit = function () {return;};
}
Then in your methods, you can probably use:
function optionA()
{
if(!myInitCalled ) // Checking if first time this is called.
{myInit();}
doA();
}
function optionB()
{
if(!myInitCalled )
{myInit();}
doB();
}
This will ensure that myInit is called only once!!

Noob javascript, why is this firing onload?

So I dont understand why the console logs 1 right away onload or something when i have one.onclick = alterIt(1) shouldn't it wait till i click one. Anyway, obviously I am not ver good at javascript, thanks for your help.
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = alterIt(1);
}
function alterIt(x) {
console.log(x);
}
When you wrote:
one.onclick = alterIt(1);
...then you invoked the alterIt function and set the return value as the onclick handler. Instead, you wanted:
one.onclick = function(){ alterIt(1) };
// ...or better yet
one.addEventListener('click',function(){ alterIt(1) },false);
When the line one.onclick = alterIt(1); is executed, alterIt(1) is actually evaluated. What you want is to bind a function to one.onclick, which is only executed when the onclick event fires. You need something like
one.onclick = function() { alterIt(1) };
which doesn't bind the result of alterIt(1) to one.onclick, but rather the result of the function evaluation.
Wrap the function call like this so it doesn't fire until click:
window.onload = initialize;
function initialize() {
if (1 == 1){
calculation();
}
}
function calculation() {
var one = document.getElementById('one');
one.onclick = function(){ alterIt(1);};
}
function alterIt(x) {
console.log(x);
}
Example fiddle: http://jsfiddle.net/RkH6Q/
There are two ways that you could code to work around this issue:
//Anonymous Closures
one.onclick = function(){ alterIt(1); };
//Bind Closures
one.onclick = alertIt.bind(window, 1);
Note: Function.bind() is supported by all the browsers for a year. If you care about old browsers, anonymous closures is the way to go.
What is happening is that you are calling the alterIt function when you should just be passing it in. So remove the parenthesis like so:
one.onclick = alterIt;

How do I call a function defined in a javascript variable

I have a function defined in a javascript variable. How do I call that function within a javascript function?
function clear_viewer() {
var stop_function = "jwplayer.stop();";
// call stop_function here
}
Thanks.
function clear_viewer() {
var stop_function = "jwplayer.stop();";
eval(stop_function);
}
You shouldn't do this though, eval should be avoided if at all possible. Instead you should do something more like this, which creates a function directly for later execution.
function clear_viewer() {
var stop_function = function() {
jwplayer.stop();
};
stop_function();
}
Could always go with the 'all evil' eval():
eval(stop_function);
Obviously you need to be very careful when using eval so that you don't wind up executing malicious code accidentally. Another option would be to turn stop_function into an anonymous function that executes your code:
var stop_function = function(){
jwplayer.stop();
};
stop_function();
function clear_viewer() {
var stop_function = function(){ jwplayer.stop();};
stop_function();
}

javascript function vs. ( function() { ... } ());

I have often see expressions such as:
(function () {
var x = 1;
...
}());
How do I interpret it? syntactically, this alone is a anonymous function definition.
function() {
...
}
what the () after that? and why put it in the enclosing ()?
Thanks
Exactly the same, except that it is being invoked immediately after being converted into a function expression.
// v-----first set of parentheses makes the function an expression
(function () {
var x = 1;
...
}());
// ^-----this set is used to invoke the function
Same as if you did:
var myfunc = function () {
var x = 1;
...
};
myfunc();
or (similar) this:
var returnValue = function () {
var x = 1;
...
}();
Get rid of the names, move the parentheses around, and you can see they're not that different.
The area where I most often find this useful is in callback functions. This notation can also used in cases where you need to include a variable in a callback function, but you need the variable state to not be affected by what goes on outside the function.
var someVal = 1;
setTimeout( (function(one) {
return function() {
alert(one); // alerts a 1 even 10 seconds after someVal++;
}
})(someVal), 10000);
someVal++; // the value in the setTimeout will remain the same as it is locked inside.
In this context, setTimeout takes a function that takes no arguments. So the question of how to pass in a value to that function is answered by creating a function that takes one argument that returns a function that takes 0 arguments.
I suggest anyone wanting to learn more about the power of this notation to play around with it in the Firebug JavaScript console. Once you wrap your head around this concept, you'll start to see areas where this powerful concept can be used.

Categories

Resources