JavaScript Foundations

History of JavaScript

  • JavaScript was created in 1995, by Brendan Eich, who was hired to do so by Netscape, the parent company of the browser Netscape Navigator.
  • It was initially named "Mocha" but then changed to "LiveScript" and finally  to "JavaScript", to ride on Java's popularity hype.
  • JavaScript was the brainchild of Netscape's owner, Mark Andreesen.
  • The idea behind creating JavaScript, was to create a language that was simple enough for amateur developers to understand, Java was not simple.
  • Later on, every browser company created a JavaScript version of their own that worked best on their browser and was miserable on other browsers (ex: Microsoft created JScript for Internet Explorer). And "Best viewed in Netscape" and "Best viewed in Internet Explorer" logos became common for most websites.

History of JavaScript

  • So Netscape, in November of 1996, submitted their JavaScript implementation to "ECMA International" and asked them to build out a standard for it. I was completed in 1997.
  • ECMA stands for European Computer Manufacturer's Association.
  • ECMA International is "an industry association founded in 1961, dedicated to the standardization of information and communication systems". It has created standards for many different things. JavaScript is just one of them.
  • ECMA named the JavaScript standard ECMA-262. The committee in ECMA that works on this standard is called TC-39 or simply Technical Committee 39. It consists of people from browser companies like Google, Mozilla, and other companies which are invested heavily in the web like Facebook, PayPal, etc.
  • ECMA uses the term "ECMAScript" (ES or es) and not "JavaScript" because Oracle has the ownership of the word "JavaScript". Hence versions of JavaScript are referred as es6 or es2016 etc.
  • The ECMA specification or the JavaScript specification.

Versions of JavaScript

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 (??)

 About JavaScript

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.

 About JavaScript

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.

 About JavaScript

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:

  1. Store data in some Data Structure (language provided or custom)
  2. Run operations on them (Algorithms) like loops or conditionals or set of them defined through functions.

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.

 About JavaScript

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)

 About JavaScript

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.

 About JavaScript

For example:

  1. Write code to get a list of all the prime numbers between 0 -100.
  2. You have a list of students and their total marks in exam. Write code to get percentage out of total marks for each student on the list.
  3. A car at location A in city, it wants to reach the location B on the other side of the city. You are given the city map, with measurements of each road. Calculate the shortest path for the car to reach location B.

 Variable Declarations In JavaScript

 Variable Declarations In JavaScript

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

 Variable Declarations In JavaScript

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";

 Variable Declarations In JavaScript

/** 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"

 Variable Declarations In JavaScript

/** 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?

  • can not start variable names with number
  • can not assign a "keyword" as variable name.
  • A "keyword" is any word which already represents something meaningful in the language.
  • can not use symbols in names, other than "$" and "_".
  • can not reassign a "const" variable. 

Primitive Data Structures in JavaScript

 Primitive Data Structures In JavaScript

  1. Strings
  2. Number
  3. Boolean
  4. Symbols
  5. BigInt
  6. undefined
  7. null

Data Structures that can store only one value.

Strings

  • 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

Numbers

  • Numbers handle all sorts of numbers, whole number, decimal etc.
  • Numbers can be written with underscores ("_")
  • Numbers can be written with e as well, e = 10
  • Numbers can work with maximum of 9007199254740991 i.e, Number.MAX_SAFE_INTEGER
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

BigInt

  • BigInt values represent numeric values which are larger than
  • Number.MAX_SAFE_INTEGER i.e, (2⁵³ - 1) and thus cannot be represented by the "number" data type.
  • A BigInt is created by appending n to the end of an integer or calling the constructor BigInt.
  • 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

Boolean

  • The boolean type has only two values: true and false.
  • A falsy (sometimes written falsy) value is a value that is always considered false when encountered in a boolean context.


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

Null

  • null forms a separate type of its own which contains only the null value.
  • In JavaScript, null is not a “reference to a non-existing object” or a “null pointer” like in some other languages ( C or C++ ). It’s just a special value which represents “nothing”, “empty” or “value unknown”.

let name = null;
alert ( name );  //  null

Undefined

  • 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

Symbol

  • A "symbol" represents a unique identifier. A value of this type can be created using Symbol() constructor.
  • At the time of creation, we can give symbols a description (also called a symbol name) to access that symbol later.
// id is a symbol with the 
// description "hello"
const id = Symbol("hello");

Symbol.for("hello")

Object Data Structures in JavaScript

 Object Data Structures In JavaScript

  1. Array,
  2. Object,
  3. Map,
  4. Set,
  5. WeakMap - not important right now,
  6. WeakSet - not important right now,
  7. Date,
  8. JSON,
  9. Class

Data Structures that can store more than 1 value or a group of values.

Array

  • 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

Object

  • 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

Map

  • 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.

Set

  • A list, similar to Array. The only difference is, Sets only have unique values.
  • If you add value that already exists, it won't get added.
// 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.
  • Object and Map are similar. So you can create an Object from a Map, and a Map from an Object as well.
  • Array and Set are similar, so you can convert one into another here as well.
  • Map and Set have similar methods like, has, get, size etc.

Date

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.
  • Methods to work with Dates in JS.
  • Almost all the languages provide built-in support for working with date and time

JSON

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.
  • JSON: JavaScript Object Notation
  • Simply, a mix of Objects and Array. Complex Objects.
  • Initially it was created for JS, but now most langauges use it.
  • It's mainly used for config files etc.
  • These 2 are very JavaScript specific.
  • They are created based on how JavaScript creates, allocates and then frees up memory  (also k/a Garbage Collection) for the data structures created in code.
  • They are basically created to prevent memory leaks with regular data structures like Objects, Maps etc.
  • We will study these in JS Deep Dive, once we have a bit of understanding of memory, allocation etc.

WeakMap and WeakSet

Class

  • Class help you create objects, but with custom properties.
  • You can create your own objects or any other data structure using classes.
  • Classes are syntactic sugar in JavaScript, over Constructor function. They have been added to resemble object oriented programming (OOP) language feature like in Java. But the OOP in Java is very different from OOP in JavaScript.
  • We will use Class for creating data structures like Linked Lists, Trees, Tries, Graphs etc.
  • Will study classes in JS Deep Dive.
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.

Data Structures Overall