Variable Identifiers

  1. Naming rules
  • Start with a letter, underscore, or $
  • Contain letters, underscores, $, and digits

Examples of valid and invalid names

1
2
3
4
5
var abc;
var _abc;
var $abc;
var _abc1$;
function $$abc_(){}
1
2
3
4
var 1abc;
var *abc;
var abc&;
function #abc(){}

Keywords and Reserved Words

Case Sensitivity

1
2
3
4
5
6
7
var Arr = [1,2,3];
var arr = function(){
For(var i = 0; i < A.length; i++){
console.log(A[i]);
}
}
for is a keyword and must be lowercase

Strict Mode

Why strict mode was introduced
Benefits

  • Removes unreasonable, loose, and unsafe parts of JS syntax, reduces quirky behavior, and keeps code running safely
  • Makes the compiler more efficient and code run faster

Usage
Enable strict mode globally

1
2
3
4
5
6
<script type="text/javascript">
"user strict";
(function)(){
console.log("hello world!");
})()
</script>

Enable strict mode inside a function

1
2
3
4
5
6
7
<script type="text/javascript">
(function)(){
"user strict";
console.log("hello world!");
})()
</script>

Differences between strict mode and normal mode

  • In strict mode, you can't implicitly declare and define variables
1
2
3
4
(function)(){
use "strict"
abc = 0 // ReferenceError
})()
  • In strict mode, objects can't have duplicate property names
1
2
3
use "strict"
var obj = {a:1,b:2,a:3}
// SyntaxError
  • You can't call arguments.callee (used for recursion in anonymous functions)
1
2
3
4
5
6
7
8
9
var count = 0;
(function)(){
user "strict"
if (count > 10){
return;
}
count++;
arguments.callee(); //TypeError
})();
  • The with statement
    1
    2
    3
    4
    5
    6
    7
    8
    var x,y;
    (function)(){
    "use strict";
    with(Math) { //TypeError
    x = cos(3 * PI) + sin (LN10);
    Y = tan(14 * E);
    }
    })();

Strict mode has other restrictions too

Comments

1
2
3
4
5
/*
This is a JS multi-line comment
Both can span multiple lines
*/
// This is a JS single-line comment