Relationship Between ECMAScript and JavaScript
In November 1996, Netscape, the creator of JavaScript, submitted the language to the ECMA International standards organization hoping to establish it as an international standard. The following year, ECMA released the first edition of standard document ECMA-262, which defined the specifications for browser scripting languages and named the language ECMAScript (version 1.0).
The standard was originally designed for JavaScript, but it was not named JavaScript for two reasons: first, the trademark "JavaScript" was already registered by Netscape; second, the naming aimed to reflect that the language was standardized by ECMA rather than Netscape, ensuring its openness and neutrality. Therefore, ECMAScript is the specification, and JavaScript is one of its implementations.
Including JavaScript in Projects
Inline Script Tags
<script>
// Write your JS logic here
</script>
External JavaScript Files
<script src="app.js"></script>
Language Conventions
Adding Comments
// This is a single-line comment
/*
This is a
multi-line comment
*/
Statement Termination
All JavaScript statements must end with a semicolon (;).
Basic Language Fundamentals
Declaring Variables
- Variable names can consist of letters, digits, underscores (
_), and dollar signs ($), but cannot start with a digit. - Use the
varkeyword to declare variables:
var userName = "Alice";
var userAge = 25;
Note:
- Variable names are case-sensitive.
- CamelCase naming is recommended.
- Reserved keywords cannot be used as variable names.
Data Types
Dynamic Typing
JavaScript variables are dynamically typed:
var data; // data is undefined
var data = 100; // data is now a number
var data = "Bob"; // data is now a string
Number Type
JavaScript does not distinguish between integers and floats; there is only one numeric type.
var price = 49.99;
var quantity = 10;
var largeNum = 123e5; // 12300000
var smallNum = 123e-5; // 0.00123
// NaN stands for "Not a Number"
var invalid = NaN;
String Type
var greeting = "Hello";
var target = "World";
var message = greeting + target;
console.log(message); // Outputs: HelloWorld
Common string methods:
| Method | Description |
|---|---|
.length |
Returns string length |
.trim() |
Removes whitespace from both ends |
.trimStart() |
Removes whitespace from the start |
.trimEnd() |
Removes whitespace from the end |
.charAt(index) |
Returns character at specified index |
.concat(str1, str2...) |
Concatenates strings |
.indexOf(substr) |
Returns index of first occurrence |
.substring(start, end) |
Extracts characters between indices |
.slice(start, end) |
Extracts section of string |
.toLowerCase() |
Converts to lowercase |
.toUpperCase() |
Converts to uppercase |
.split(separator) |
Splits string into array |
Diffference Between slice() and substring()
Both methods extract parts of a string, but behave differently with invalid inputs:
- If
start > stop:substring()swaps the parameters.slice()returns an empty string.
- Negative indices:
substring()treats them as0.slice()counts from the end of the string.
Boolean Type
Unlike Python, boolean values are lowercase: true and false.
var isActive = true;
var isDeleted = false;
Falsy values include: "" (empty string), 0, null, undefined, and NaN.
Null vs Undefined
nullrepresents an intentional absence of value. It can be assigned to clear a variable.undefinedmeans a variable has been declared but not assigned a value, or a function returns nothing.
Objects and Arrays
Arrays store multiple values in a single variable, similar to Python lists.
var colors = ["red", "green", "blue"];
console.log(colors[1]); // Outputs: green
Common array methods:
| Method | Description |
|---|---|
.length |
Returns array size |
.push(item) |
Adds item to end |
.pop() |
Removes last item |
.unshift(item) |
Adds item to beginning |
.shift() |
Removes first item |
.slice(start, end) |
Returns shallow copy |
.reverse() |
Reverses array order |
.join(separator) |
Joins elements into string |
.concat(arr1, arr2...) |
Merges arrays |
.sort(compareFn) |
Sorts elements |
.forEach(callback) |
Executes function for each element |
.splice(start, deleteCount, items...) |
Changes content of array |
.map(callback) |
Creates new array with results |
Using forEach()
Syntax: forEach(callbackFn, thisArg)
colors.forEach(function(item, index, array) {
console.log(index + ": " + item);
});
Using map()
Syntax: map(callbackFn, thisArg)
var lengths = colors.map(function(item) {
return item.length;
});
Important Note on sort()
By default, sort() converts elements to strings and sorts by Unicode code points. To sort numbers correctly, provide a compare function:
function compareNums(a, b) {
return a - b;
}
var numbers = [33, 11, 55, 22];
numbers.sort(compareNums);
Loop through arrays:
var items = [100, 200, 300];
for (var idx = 0; idx < items.length; idx++) {
console.log(idx);
}
ES6 introduced Symbol, a new primitive type representing unique values, making it the 7th data type in JavaScript.
Check types using typeof:
typeof "hello" // "string"
typeof null // "object"
typeof false // "boolean"
typeof 42 // "number"
Operators
Arithmetic Operators
+ - * / % ++ --
var counter = 5;
var result1 = counter++; // result1 = 5, counter becomes 6
var result2 = ++counter; // counter becomes 7, result2 = 7
Comparison Operators
> >= < <= != == === !==
Note:
==performs type coercion (loose equality).===checks both value and type (strict equality).
1 == "1" // true
1 === "1" // false
Logical Operators
&& || !
Assignment Operators
= += -= *= /=
Control Flow
if-else
var score = 80;
if (score >= 60) {
console.log("Passed");
} else {
console.log("Failed");
}
if-else if-else
var temp = 15;
if (temp > 30) {
console.log("Hot");
} else if (temp < 10) {
console.log("Cold");
} else {
console.log("Moderate");
}
switch Statement
var dayNum = new Date().getDay();
switch (dayNum) {
case 0:
console.log("Sunday");
break;
case 1:
console.log("Monday");
break;
default:
console.log("Other day");
}
Always include break to prevent fall-through.
for Loop
for (var i = 0; i < 5; i++) {
console.log(i);
}
while Loop
var count = 0;
while (count < 5) {
console.log(count);
count++;
}
Ternary Operator
var a = 10, b = 20;
var max = a > b ? a : b;
// Nested ternary
var result = a > b ? a : (b === 20 ? a : b);
Functions
Defining Functions
// Standard function
function greet() {
console.log("Hello!");
}
// Function with parameters
function multiply(x, y) {
console.log(arguments); // built-in arguments object
return x * y;
}
// Anonymous function
var divide = function(x, y) {
return x / y;
};
// Immediately Invoked Function Expression (IIFE)
(function(msg) {
console.log(msg);
})("IIFE executed");
Arrow Functions (ES6)
var double = val => val * 2;
// Equivalent to:
var double = function(val) {
return val * 2;
};
// Multiple parameters
var add = (a, b) => a + b;
// No parameters
var getNum = () => 42;
Arguments Object
function sumAll() {
let total = 0;
for (let i = 0; i < arguments.length; i++) {
total += arguments[i];
}
return total;
}
sumAll(1, 2, 3); // Returns 6
Functions can only return one value. Return multiple values by packaging them in an object or array.
Variable Scope
- Local variables: Declared inside a function with
var; accessible only within that function. - Global variables: Declared outside functions; accessible everywhere.
Lifetime:
- Local variables are destroyed after function execution.
- Global variables persist until the page closes.
Scope lookup follows the chain: inner function → outer function → global.
var region = "Asia";
function outer() {
var region = "Europe";
function inner() {
var region = "Africa";
console.log(region); // Outputs: Africa
}
inner();
}
outer();
Closures
function outerFunc() {
var secret = "hidden";
function innerFunc() {
console.log(secret);
}
return innerFunc;
}
var closure = outerFunc();
closure(); // Outputs: hidden
Lexical Analysis (Simplified)
When a function is called, JavaScript creates an Activation Object (AO) and:
- Adds parameters (set to
undefinedif not passed). - Adds local variables (set to
undefinedif not declared). - Adds function declarations (overwriting any same-named properties).
var num = 10;
function test() {
console.log(num); // undefined
var num = 20;
console.log(num); // 20
}
test();
Built-in Objects
Object Basics
Objects are collections of key-value pairs. Keys are strings by default.
var user = { name: "Charlie", age: 30 };
console.log(user.name);
console.log(user["age"]);
Iterate over objects:
for (var key in user) {
console.log(key + ": " + user[key]);
}
Create objects:
var person = new Object();
person.name = "Diana";
person.age = 28;
ES6 Map allows keys of any type:
var map = new Map();
var objKey = { id: 1 };
map.set(objKey, "Value associated with object");
map.get(objKey); // Returns the value
Inheritance Example
// Parent
function Vehicle(location) {
this.location = location;
}
Vehicle.prototype.move = function() {
this.location++;
};
// Child
function Truck(location) {
Vehicle.call(this, location);
}
Truck.prototype = Object.create(Vehicle.prototype);
Truck.prototype.constructor = Truck;
Truck.prototype.load = function() {
console.log("Loading cargo");
};
Date Object
// Current date
var now = new Date();
console.log(now.toLocaleString());
// From string
var past = new Date("2020/01/01 10:00");
// From milliseconds
var fromMs = new Date(10000);
// Specific components
var specific = new Date(2023, 5, 15, 9, 30, 0);
Common Date methods:
var d = new Date();
d.getDate(); // Day of month
d.getDay(); // Weekday (0-6)
d.getMonth(); // Month (0-11)
d.getFullYear();// Year
d.getHours(); // Hours
d.getMinutes(); // Minutes
d.getSeconds(); // Seconds
d.getTime(); // Milliseconds since epoch
RegExp (Regular Expressions)
var pattern1 = new RegExp("^[a-z]+$");
var pattern2 = /^[a-z]+$/;
pattern1.test("hello"); // true
// Global flag note
var globalPattern = /test/g;
globalPattern.test("test test"); // true
globalPattern.lastIndex; // Points to after first match
Math Object
Math.abs(-5); // 5
Math.floor(4.7); // 4
Math.ceil(4.2); // 5
Math.round(4.5); // 5
Math.max(10, 20); // 20
Math.min(10, 20); // 10
Math.random(); // Random number between 0 and 1
Math.pow(2, 3); // 8
Math.sqrt(9); // 3