Archive

Archive for the ‘Javascript’ Category

Reserved keywords in JavaScript

February 21, 2013 Leave a comment

List of all reserved words in JavaScript

ECMAScript 1

Source : EcmaSciprt 1 It listed the following reserved words

do
if
in
for
new
try
var
case
else
enum
null
this
true
void
with
break
catch
class
const
false
super
throw
while
delete
export
import
return
switch
typeof
default
extends
finally
continue
debugger
function

ECMAScript 2

Later, ECMAScript 2 added intbytechargotolongfinalfloatshortdoublenative,publicstaticthrowsbooleanpackageprivateabstractvolatileinterfaceprotected,transientimplementsinstanceof, and synchronized.

do
if
in
for
int
new
try
var
byte
case
char
else
enum
goto
long
null
this
true
void
with
break
catch
class
const
false
final
float
short
super
throw
while
delete
double
export
import
native
public
return
static
switch
throws
typeof
boolean
default
extends
finally
package
private
abstract
continue
debugger
function
volatile
interface
protected
transient
implements
instanceof
synchronized

ECMAScript 3

ECMAScript 3 introduced no changes in the list of reserved keywords — it’s identical to the ECMAScript 2 keywords.

ECMAScript 4

There is no such thing as ECMAScript 4.

ECMAScript 5

ECMASCript 5/5.1 removed intbytechargotolongfinalfloatshortdoublenative,throwsbooleanabstractvolatiletransient, and synchronized; it added let, and yield.

do
if
in
for
let
new
try
var
case
else
enum
eval
null
this
true
void
with
break
catch
class
const
false
super
throw
while
yield
delete
export
import
public
return
static
switch
typeof
default
extends
finally
package
private
continue
debugger
function
arguments
interface
protected
implements
instanceof

Note that implementsletprivatepublicinterfacepackageprotectedstatic, and yield are disallowed in strict mode only.

You may have noticed I included eval and arguments in the list. These are not strictly reserved words, but they sureact like them — they’re disallowed in strict mode too.

Also, the (unlisted) NaNInfinity, and undefined properties of the global object are immutable or read-only properties in ES5. So even though var NaN = 42; in the global scope wouldn’t throw an error, it wouldn’t actually do anything. To avoid confusion, I’d suggest avoiding the use of these identifiers altogether, even though they’re not strictly reserved words.

ECMAScript 6

At the time of writing, the latest ECMAScript 6 draft still lists the same reserved keywords as in ECMAScript 5/5.1.

What’s the use?

Reserved keywords may not be used as variable names in JavaScript. For optimal backwards compatibility with older JavaScript engines, it’s best to avoid using the keywords on this page as variable names or property names 

 

Advertisements
Categories: Javascript Tags:

How to create Ctrl+Key shortcuts in Javascript

October 4, 2010 Leave a comment

Here is the simple code that allows you to capture when a desired set of keys are pressed. In this example, we are focusing on CTRL+S, but it can be expanded easily with just a few lines of code per shortcut you wish to add.

var isCtrl = false;

document.onkeyup=function(e){

if(e.which == 17) isCtrl=false;

}

document.onkeydown=function(e){

if(e.which == 17) isCtrl=true;

if(e.which == 83 && isCtrl == true) {

//run code for CTRL+S — ie, save!

return false;

}

}

jQuery Code

Here is an example of how to create a Ctrl+Key based shortcut within javascript using the jQuery Library.

var isCtrl = false;
$(document).keyup(function (e) {
if(e.which == 17) isCtrl=false;
}).keydown(function (e) {
if(e.which == 17) isCtrl=true;
if(e.which == 83 && isCtrl == true) {
//run code for CTRL+S — ie, save!
return false;
}
});

Explanation

This code is quite simple but let me explain it a little bit. Whenever a key is pressed down, we first check to see if its CTRL being pressed (key code 17). If it is CTRL, then we set isCtrl to true in order to keep track when CTRL is activated, and of course we return isCtrl back to false once CTRL is released via the keyup event. We must keep track of the CTRL activity with a variable because the event will fire on a per-key basis. When you press ctrl+S for example, the event fires twice with two different key codes – making it impossible to simply check for both keys in one swift action.

Now going back to the keydown event; after the CTRL key check, we can look to see if other keys are being pressed. In this example, key code 83 is for the S key, which in one example could be useful for allowing quick saving of a form. And lastly, the return false; plays a very important role in keeping the browser from picking up that particular key combination and acting on it. In the example above of using CTRL+S, normally when you press that the browser will prompt you to save the page – but with the return false, the browser backs down and stays quiet.

Library

As posted in the comments, there is a nice library to get this done over at openjs.com. If your looking for a simple solution that covers all angles, check out Handling Keyboard Shortcuts in JavaScript

Javascript Key Codes

Key Pressed Key Code
backspace 8
tab 9
enter 13
shift 16
ctrl 17
alt 18
pause/break 19
caps lock 20
escape 27
page up 33
page down 34
end 35
home 36
left arrow 37
up arrow 38
right arrow 39
down arrow 40
insert 45
delete 46
0 48
1 49
2 50
3 51
4 52
5 53
6 54
7 55
8 56
9 57
a 65
b 66
c 67
d 68
e 69
f 70
g 71
h 72
i 73
j 74
k 75
l 76
m 77
n 78
o 79
p 80
q 81
r 82
s 83
t 84
u 85
v 86
w 87
x 88
y 89
z 90
left window key 91
right window key 92
select key 93
numpad 0 96
numpad 1 97
numpad 2 98
numpad 3 99
numpad 4 100
numpad 5 101
numpad 6 102
numpad 7 103
numpad 8 104
numpad 9 105
multiply 106
add 107
subtract 109
decimal point 110
divide 111
f1 112
f2 113
f3 114
f4 115
f5 116
f6 117
f7 118
f8 119
f9 120
f10 121
f11 122
f12 123
num lock 144
scroll lock 145
semi-colon 186
equal sign 187
comma 188
dash 189
period 190
forward slash 191
grave accent 192
open bracket 219
back slash 220
close braket 221
single quote 222

30 best practices to boost your web application performance

June 18, 2010 1 comment
  1. Limit interaction with DOM as much as possible. Store DOM references in local JavaScript variables before using them if you need them more than once. Consider setting innerHTML over document.createElement/appendChild().
  2. eval() is evil. So is the constructor new Fuction(). Avoid them to the maximum extent.
  3. Say no to with statement. It introduces an extra scope to search each time variable is referenced and the contents of that scope is not known at compile time.
  4. Consider for() over for-in loop. The for-in loop requires the script engine to build a list of all the enumerable properties and check for duplicates prior the start.
  5. Instead of putting try-catch inside a loop, put the loop inside a try-catch. Exception handling should be done at as high level in the script where it does not occur frequently.
  6. Even the holy Bible mentions this – NO Globals. Variable in the global scope persist though the life time of the script, whereas in local scope they are destroyed when the local scope is lost. Also when a global variable is referenced inside a function or another scope, the script engine has to search through the whole scope to find it.
  7. fullName += ‘John’; fullName += ‘Holdings’; is faster than fullName += ‘John’ + ‘Holdings’;
  8. But if you have multiple string concatenations, prefer pushing to an Array and then calling the join() method on it. This is particularly helpful while building HTML snippets.
  9. For simple tasks, prefer Primitive operations over function calls e.g. val1 < val2 ? val1 : val2; is faster than Math.min(val1, val2); and similarly myArr.push(newEle); is slower than myArr[myArr.length] = newEle;
  10. A function reference perform better than (hard coded) string literals as parameters to setTimeout() and setInterval(). E.g. setTimeout(“someFunc()”, 1000) will perform slower than setTimeout(someFunc, 1000)
  11. Avoid DOM modifications while traversing. The DOM element lists returned by functions like getElementsByTagName() are live; so changing these collections won’t wait for execution to finish first. This might also cause an infinite loop to occur.
  12. Store references to object members (properties and even methods) if you are going to need it more than once e.g. var getTags = document.getElementsByTagName; getTags(‘div’);
  13. Store local references to out-of-scope variables to provide quicker access and avoid lookup. E.g.
        var a = ‘something’;
     
        function foo() {
            //create a local reference for ‘a’, which is out-of-scope of this function
            var l = a;
            
            //do something with l
        }
  14. for(var i=0; i < someArray.length; i++) {…} is slower than for (var i=0, loopLen=someArray.length; i<loopLen; i++) {…}.
  15. Add Expires and max-age directive of Cache-Control HTTP Header in server responses.
  16. Optimize CSS. Prefer <link> over @import. Refer to this beautiful presentation http://www.slideshare.net/stubbornella/object-oriented-css
  17. Use CSS sprites to cut down on image resources
  18. GZip .js and .css files. On Apache if you set something like this in .htaccess, it will also gzip your HTML, XML and JSON
    AddOutputFilterByType DEFLATE text/html text/css text/plain text/xml application/x-javascript application/json
  19. Use JavaScript minifier. Apart from YUI and JSMin, also try Google Closure http://closure-compiler.appspot.com/home (Courtesy: James Westgate, a fellow reader)
  20. Optimize each and total number of resources for every view and split them across sub-domains to enable parallel downloads. For more information on parallel downloads, read this http://yuiblog.com/blog/2007/04/11/performance-research-part-4/
  21. Put stylesheets at the top to help progressive rendering on many browsers including IE
  22. Try to keep your DOM structure as light as possible. The size of DOM slows down all the operations related to it such as reflowing, traversal and DOM manipulation. document.getElementsByTagName(‘*’).length should return as small value as possible.
  23. Pay attention to the selectors you use. E.g. if you are trying to collect the list items which are direct children of an unordered list, use jQuery(“ul > li”) rather than jQuery(“ul li”)
  24. While toggling element visibility (display) remember this: element.css({display:none}) is faster than element.hide() or element.addClass(‘myHiddenClass’). But unless you are using it inside a loop, I vote for element.addClass(‘myHiddenClass’) because it keeps your HTML clean – remember that thumb rule from my earlier article? No inline CSS or JavaScript.
  25. When you are done with variable references to DOM, nullify them. JavaScript leaves that power with you.
  26. With AJAX, GET works faster than POST. So prefer GET wherever you can. Just keep in mind IE restricts the GET request length to 2K.
  27. Go easy on scripted animations. Animation without hardware support is slow. Try to avoid excessive use of animations which do not bring any real usability value.
  28. Avoid background-repeat if the background-image is small relative to its containing element. Interaction such as scrolling is extremely slow if background-repeat property is set to repeat-x or repeat-y combined with a background-image of a size which needs to be repeated multiple times to fill in the element’s background. Try a commonly used CSS pattern to have a big enough background-image with background-repeat: no-repeat.
  29. Do not use <table>s for layout. <table>s often require multiple passes before the layout is completely established because they are one of the rare cases where elements can affect the display of other elements that came before them on the DOM. And for data tables, use table-layout:fixed; this will allow a more efficient layout algorithm and let the table render row by row according to the CSS 2.1 specification.
  30. Always fall back to core JavaScript whenever possible. Limit framework usage.

Categories: Javascript