Ver | Official Name | Description |
---|---|---|
ES1 | ECMAScript 1 (1997) | First edition |
ES2 | ECMAScript 2 (1998) | Editorial changes |
ES3 | ECMAScript 3 (1999) | Added regular expressions, Added try/catch, Added switch, Added do-while |
ES4 | ECMAScript 4 | Never released |
ES5 | ECMAScript 5 (2009) | Added "strict mode", Added JSON support, Added String.trim(), Added Array.isArray(), Added Array iteration methods, Allows trailing commas for object literals |
ES6 | ECMAScript 2015 | Added let and const, Added default parameter values, Added Array.find(), Added Array.findIndex() |
ECMAScript 2016 | Added exponential operator (**), Added Array.includes() | |
ECMAScript 2017 | Added string padding, Added Object.entries(), Added Object.values(), Added async functions, Added shared memory, Allows trailing commas for function parameters | |
ECMAScript 2018 | Added rest / spread properties, Added asynchronous iteration, Added Promise.finally(), Additions to RegExp | |
ECMAScript 2019 | String.trimStart(), String.trimEnd(), Array.flat(), Object.fromEntries, Optional catch binding | |
ECMAScript 2020 | The Nullish Coalescing Operator (??) |
JavaScript is a scripting language.
A scripting language is something that can be inserted into some other file or system and do some stuff.
Initially JavaScript was created with the sole purpose of being inserted into the HTML doc or the Website.
Programming is all about data and operations to be done on that data like creating data, updating data, deleting data, reading data (CRUD).
That's why from the CPU level itself, we have memory (RAM, ROM), and ALU (arithmetic logic unit) as the main components of CPU.
Programming languages are mediums to access that CPU memory for storing data and CPU processor for running operations on/with that data.
These languages, broadly, do 2 things primarily:
There are more than 200 programming languages in the world (a Wiki list), all of them are doing the same set of steps in different ways.
When we talk about JavaScript, like any other language, it can be studied in similar 2 broad parts:
Data Structures | Algorithms |
---|---|
Declarations for Data Structures (var, let, const) | Loops |
Primitive Data Structures (strings, numbers, bigint, boolean, null, undefined, symbol) |
Conditionals |
Object Data structures (array, object, map, set, weakmap, weakset, date, JSON, class) |
Functions (for all the custom logic) |
Almost all the languages provide some language specific custom data structures, for example in JS, we have Promises, Proxy, Modules etc.
Then there are some data structures which are not provided by the language directly, but they are very useful. They need to be implemented manually. Eg: Linked Lists, Trees, Graphs, Tries (Prefix Trees), Heaps, Stacks etc.
Algorithm: Any logic that we write in code, simplest to the most complex, all of them are algorithms. Basically any code that does some operation on some data is an algo.
For example:
var, let and const
var | let | const |
---|---|---|
old way, ever since JS was created | new way, added in es6 (2015) | new way, added in es6 (2015) |
variables created can be re-assigned | variables created can be re-assigned | variables once created can not be re-assigned |
has only function scope | has block scope | has block scope |
can be left without value | can be left without value | can not be left without a value |
Do not use unless absolutely required | Preferred | Most preferred |
const newConstValue = "one"
let newLetValue = "two"
var newVarValue = "three"
/** only "Declaring" the variables,
* not initialising */
let newLetValue;
var newVarValue;
/** "Initialising" the variables using
* the assignment operator (=) */
newLetValue = "two"
newVarValue = "three"
/** not valid */
const newConstValue;
newConstValue = "three";
/** Only valid */
const newConstValue = "three";
/** Other possible syntaxes with "const", "let" and "var": */
/** Declaration first, Initialisation on the next line */
let userName;
userName = "Differ"
var userName;
userName = "Differ"
/** multiple variable "declaration and initialisation" in single line*/
let myName = "Yash", age = 29, profession = "software development";
var myName = "Yash", age = 29, profession = "software development";
/** Declaration first, Initialisation on the next line */
let myName, age, profession;
myName = "Yash", age = 29, profession = "software development";
var myName, age, profession;
myName = "Yash", age = 29, profession = "software development";
/** can be re-assigned*/
let oneVariable = "one"
oneVariable = "two"
oneVariable = "three"
var oneVariable = "one"
oneVariable = "two"
oneVariable = "three"
/** can not start variable names with number */
const 1stName = "Yash"
// Not Valid, cannot use number in the start of a variable names
//
const upd8User = "new user"
// Valid, can use number in variable names
/** can not assign a "keyword" as variable name. */
const string = "a string value"
// "string" is a keyword in javascript
/** can not use symbols in names, other than "$" and "_". **/
const my@email = "mail@gmail.com"
// invalid use of "@"
//
const dollar$ = "50 U.S dollars"
// Valid use of "$" symbol
//
const my_name = "valid variable"
// Valid use of "_" symbol
/** can not reassign a "const" variable. */
What you can NOT do while creating variables?
Data Structures that can store only one value.
Double and single quotes are "simple" quotes. There's practically no difference between them in JavaScript.
Backticks or String literals or Template strings are "extended functionality" quotes. They allow us to use JS variables and expressions into a string (String interpolation) by wrapping them in ${…} .
Using Template strings we can increase the string to multiple lines, which is not allowed with single or double quotes.
let str = "WebMasters"; // WebMasters
let str2 = 'Single quotes are good'; // Single quotes are good
let phrase = `How are you ${str}?`; // How are you Eshaan?
str.length // 10
//returns length of string, including space
let intNum = 3;
// Data type is Number & is an integer
let floatNum = 3.63;
// Data type is Number & is a floating point
let num1 = 2_4;
let num2 = 200_300_123
let billion = 1_000_000_000;
e = *(10**x)
let billion = 1e9;
// 1 * (10 ** 9) = 1 billion, 1,000,000,000
//
alert( 7.3e9 );
// 7.3 * (10 ** 9) = 7.3 billions
// (same as 7300000000 or 7_300_000_000)
let num = 77_34.5e4
// 77_34.5 * (10 ** 4) hybrid example
//
let mcs = 8.94e-6;
// 8.94 * 10 ** -6 divides by 1 with 6 zeroes
// Convert any data type to number
const numericString = Number("36")
const numericString = parseInt("36")
// Rounding:
const floatNumber = 16.34
const roundedNumber = Math.round(floatNumber) // 16
const roundedNumber = Math.ceil(floatNumber) // 17
const roundedNumber = Math.floor(16.79) // 16
const random = Math.random() // 0 - 1
All mathematical operations on bigints return bigints.
We cannot mix and use typical numbers with BigInts
let num1 = BigInt(5)
alert( num1 ) // 5n
let num2 = BigInt(5.3)
// Error: BigInt can only be an integer.
//
alert(1n + 2) // Error
let keyFieldChecked = true; // yes, key field is checked
let propertyFieldChecked = false; // no, property field is not checked
let greater = 10 > 6;
console.log( greater ); // true (the comparison result is 1)
let greater = 10 < 6;
console.log( Number(greater) ); // 0 - comparison result
let name = null;
alert ( name ); // null
The meaning of undefined is “value is not assigned”.
‘undefined’ is a special keyword in JS. If a variable is declared, and unless a value is assigned to it, its value is undefined
let age;
alert ( age ); // undefined
age = 10;
alert( age ); // 10 (number)
age = undefined;
alert ( age ); // undefined
// id is a symbol with the
// description "hello"
const id = Symbol("hello");
Symbol.for("hello")
Data Structures that can store more than 1 value or a group of values.
Also called as list.
Stores items in sequence (index), starts from 0.
For CRUD operations:
const numbersList = [1,2,3,4,5]
let alphabets = ["A","b","e","a","asdasdasda"]
const mixed = ["A",123,"e",false, [1,2,3], "end"]
arr.length
// - no of elements in array.
arr[1]
// - returns the value at index 1
arr.push()
// - adds element at the end,
// returns length of new array
arr.pop()
// - removes 1 element element at the end,
// returns removed element
arr.shift()
// - removes 1 element at the start,
// returns removed element
arr.unshift()
// - adds element at the start,
// returns length of new array
Also called dictionary or hash-table
stores key-value pairs,
keys are always sorted, ascending
keys are always unique
In JS, object keys can only be strings or anything that can be converted to string directly like 1, true etc.
const newObj = {
"name": "Yash",
age: 30,
address: "Indrapuri"
}
// getting keys and values
Object.keys(newObj) =
["name", "age", "address"]
Object.values(newObj) =
["Yash", 30, "Indrapuri"]
newObj[age] // square bracket notation
newObj.age // dot notation
// returns the value of the key,
// if present, else undefined
// add new key, value in an object
newObj[email] = "new@mail.com"
newObj.phone = 9876543210
// if the key is already present
// then it updates its value,
// if not present then adds key, value
// remove a key vakue from Object:
delete newObj[phone]
delete newObj.age
Similar to Objects, but it can have non-string keys also.
Also called as Tuple
// Create a Map
let testMap = new Map();
const receipeMap = new Map([
['cucumber', 500],
['tomatoes', 350],
['onion', 50]
]) // array of arrays is a Map, 2D array
// Add value in a map
testMap.set('1', 'str1');
// a string key,
// returns the map with newly added value
testMap.set(1, 'num1'); // a numeric key
testMap.set(true, 'bool1'); // a boolean key
//the map: {'1' => 'str1', 1 => 'num1', true => 'bool1'}
// Get a key's value from Map
testMap.get(1) // "num1"
testMap.get("1") // "str1"
// get all keys of Map
testMap.keys()
// returns all the keys in an array
testMap.values()
// returns all the values in an array
testMap.entries()
// returns all the [key, value] set in an array
receipeMap.has('cucumber')
// – returns true if the key exists,
// false otherwise.
receipeMap.delete('onion')
// – removes the element (the key/value pair).
receipeMap.clear()
// – removes everything from the map.
receipeMap.size
// – returns the current element count.
// Create new set
const nameSet = new Set()
const nameSet = new Set(["Harry", "Ron", "Draco"])
// – creates the set,
// and if an array is provided,
// creates a Set from it
nameSet.add("Hermione")
// – adds a value, returns the set itself.
nameSet.delete("Draco")
// – removes the value,
// returns true if value existed and got deleted,
// else false.
nameSet.has("Harry")
// – returns true if the value exists, else false.
nameSet.clear()
// – removes everything from the set.
nameSet.size
// – is the elements count.
const rightNow = new Date()
// returns current date with time
rightNow.getFullYear()
// Get the year (4 digits)
rightNow.getMonth()
// Get the month, from 0 to 11.
rightNow.getDate()
// Get the day of month,
// from 1 to 31
rightNow.getHours(),
rightNow.getMinutes(),
rightNow.getSeconds(),
rightNow.getMilliseconds()
// Get the corresponding time components.
const student = {
name: 'John',
age: 30,
isAdmin: false,
courses: ['html', 'css', 'js'],
spouse: null
};
const stringifiedObject = JSON.stringify(student)
// to convert objects into JSON.
const jsonObject = JSON.parse(stringifiedObject)
// to convert JSON back into an object.
class Animal {
constructor(name) {
this.name = name;
}
speak() {
console.log(`${this.name} makes a noise.`);
}
}
class Dog extends Animal {
constructor(name) {
super(name); // call the super class constructor and pass in the name parameter
}
speak() {
console.log(`${this.name} barks.`);
}
}
const d = new Dog("Mitzie");
d.speak(); // Mitzie barks.