In this blogs post, I will dump whatever new things I learnt in JS. So you might find this blogs get updated more often.
JS Engine
JS Engines are the ones that can convert the human readable JS code to machine understandable code. There are some engines on web like v8 and Spider Monkey. However we are going to install NodeJS that will do the same for us.
check node version
node -v
Run JS script using node command
node script.js
Suppose script file just has one console.log(”Hello World!”) statement. Above command will convert the JS Code into machine code and execute the code. You will see hello world printed on console.
ECMAScript
European Computer Manufacturers Association, ECMAScript specification is a blueprint to create scripting languages. JS is an implementation of that blueprint.
Variables and Datatypes
Variables are used to reserve some memory to store something.
var fullName = "Bharat";
var courseCount = 0;
var isLoggedInFromGoogle = false;
Above statement simply means we reserved some memory and named it fullName. And that fullName variables is pointing to the data “Bharat” stored at that memory location.
In JavaScript variables can be declared as var, let and const. var is used to support older browsers only.
var
- can be redeclared
var x = 'Hello world'
console.log(x)
var x;
x = 9
console.log(x)
- can be reassigned
var x = 'Hello world'
x = 5
console.log(x)
- can be used before declaring
x = 'Hello world'
console.log(x)
var x;
let
- cannot be redeclared
let x = 'Hello world'
console.log(x)
let x;
- can be reassigned
let x = 'Hello world'
x = 'Learn JS'
console.log(x)
- cannot be used before declaring
try {
x = 'Hello world'
let x;
} catch (err) {
console.log(err)
}
// ReferenceError: Cannot access 'x' before initialization
The variable x declared with either let/const is hoisted at the top but not initialised, meaning the code block is aware that some x named variable exists but since it is not declared yet, it will give ReferenceError stating that we need to declare it first. Javascript only hoists declaration and not initialisations.
- cannot be used outside the block in which it is declared
try {
let x = 'Hello world'
} catch (err) {
console.log(err)
}
console.log(x)
// it will print 'null' since x was declared in try { } block scope
const
- cannot be redeclared
try {
const x = 'Hello world'
const x = 5
} catch (err) {
console.log(err)
}
// The symbol "x" has already been declared
- cannot be reassigned
- cannot be used before declaring
try {
x = 'Hello world'
const x;
} catch (err) {
console.log(err)
}
// Cannot assign to "x" because it is a constant
- cannot be used outside the block in which it is declared
try {
const x = 'Hello world'
} catch (err) {
console.log(err)
}
console.log(x)
// it will print 'null' since x was declared in try { } block scope
There are 2 scopes before ES6 (2015) announced.
- Global Scope
- Function Scope
In ES6, let and const are introduced, which are block scope.
let and const variables cannot be used outside the block scope
in which they originally declared.
Operators
var num1 = 7;
var num2 = 6;
console.log(num1 + num2);
console.log(num1 * num2);
console.log(num1 / num2);
var answer = num1 > num2;
console.log(answer)
var listingPrice = 799;
var sellingPrice = 199;
var discountPercent = ((listingPrice - sellingPrice) / listingPrice) * 100
console.log(`
listingPrice is: ${listingPrice}
SellingPrice is: ${sellingPrice}
Discount % is: ${discountPercent}
`)
var displayDiscountPercentage = Math.round(discountPercent)
console.log(displayDiscountPercentage + "% off")
Type and Operator Precedence
var result = listingPrice > sellingPrice
console.log(typeof result) //it will print boolean
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/Operator_precedence
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Operators/typeof
Conditionals
var temperature;
temperature = 39;
// var result = temperature < 20;
// console.log(result)
if (temperature < 20) {
console.log("It's very cold outside");
}
if (temperature < 30) {
console.log("It's moderate outside");
} else {
console.log("It's hot outside");
}
var email = true;
var facebook = false;
var google = false;
if(email || facebook || google) {
console.log("login success");
}
Ternary Operator
var authenticated = true;
// if(authenticated) {
// console.log("Show sign out button");
// } else {
// console.log("Show sign in option");
// }
authenticated ? console.log("Show sign out button") : console.log("Show sign in option");
console.log(`Show ${ authenticated ? "Sign out" : "Sign In"} button`);
Switch for Role Based Access
var user = "admin";
switch (user) {
case "admin":
console.log("You get full access");
break;
case "subadmin":
console.log("get access to create/delete courses");
break;
case "testprep":
console.log("get access to create/delete tests");
break;
case "user":
console.log("get access to consume the content");
break;
default:
console.log("Trial user");
break;
}
if break is removed from first admin condition then all lines below admin condition will execute till either a default or break lines comes.
Coercion and falsy values in JS
//falsy values
undefined
null
0
''
NaN //Not a number
var user = undefined; // = null, 0, '', NaN
if(user) {
console.log("Condition is true");
}
console.log(2 + 2) //22
console.log("2" + 2) //22
var x = "2";
if(x == 2) { //loose check
console.log("x == 2 Condition is true");
}
if(x === 2) { //strict check
console.log("x === 2 Condition is true");
}
Functions
function sayHello(name) {
console.log(`Hello there, ${name}. How are you?`);
}
sayHello("Bharat"); //name will be Bharat
sayHello();//name will be undefined.
function namastey() {
return "Hello in India";
}
namastey(); //nothing will be printed, since returned value not used.
var greetings = namastey();
console.log(greetings);
console.log(namastey());
Context in JavaScript
/*
sayHello(); //runs fine. If called at top. This is because of global context.
function sayHello() {
console.log("Hello");
}
*/
if (2 === 2) {
console.log("This is true");
}
var myName = "Bharat";
if (myName === myName) {
console.log("A true statement");
}
//it will give an ReferenceError: window is not defined
//because window context is not there, since we are runnings this code in node. If we had run this code in 'Console' of browser then it would have printed the log, since in browser the window context is present.
//window object is tied with browsers.
/* if(myName === window.myName) {
console.log("A true statement");
}
*/
var num = 2; //global context
function sayMe() {
console.log("say me")
}
sayMe() //execution context. When job of execution context is done then it will go away.
/**
* Execution Context
* 1. Variable Object
* 2. Scope Chain
* 3. this
*
* Rule1: Function declarations are scanned and made available.
* Rule2: Variable declarations are scanned and made undefined.
*/
//calling on top before writing funciton would work
//because the global context scans the function and made it available.
tipper("5") //print 10
tipper(5) //print 10
tipper("a") //print NaN
function tipper(a) {
var bill = parseInt(a);
console.log(bill + 5);
}
//bigTipper("200") //TypeError: bigTipper is not a function
//because: Variable declarations are scanned and made undefined.
var bigTipper = function (a) {
var bill = parseInt(a);
console.log(bill + 15);
}
console.log(name);
var name = "Bharat";
function sayName() {
var name = "Mr. Bharat";
console.log(name);
}
sayName();
console.log(name);