JavaScript

JavaScript Basics – 1

Data types in JavaScript are 2 main types. Total 10 types

1) 2 Nonprimitieve / object type – Object & Array (You can say object & array is a data structure, not data type as it stores the data types with values)

2) 7 Primitive -/ non-object type – String, Number, Boolean, Null, Undefined, Bigint, Symbol

Set & Map are data structures, not data types. so we need to know the difference between data types & data structures.

It is interesting to notice: Data types don’t store the value of data; they represent only the type of data that is stored. Data structures hold the data along with their values. They occupy space in the main memory of the computer. Also, data structures can hold different types of data within one single object.

We have a JS cheat sheet in the footer menu. Check that for easy understanding. This whole article covers chapters 1 to 100 from my Udemy course.

JS can generate many types of warnings and errors in the console. It’s best practice to identify all possible errors before we run the code and for that, we are writing a code line on top of the JS file

'use strict';

Return:

After the return statement in the function, nothing is going to be executed further in the same function, No matter if you have a valid code. It shifts the control back to the line where a function is called.

Templare literals “ & ${var}

console.log('I am happy with my salary ' + realInt + ' Thanks!');
console.log(`I am happy with my salary ${realInt}, Thank you!`);

Declare Variables in JS

let myAge = 35; Value may be changed but can’t redeclare the same variable name

var yourAge = 34; Value may be changed and also Can redeclare with the same variable name so this is not advisable to use.

const thisYear = 2023; This can’t redeclare or can’t change the value itself

Scope in js 1) Block scope 2) Function scope & 3) Global scope

Block Scope:

for (let i = 1; i < 11; i++) {
  console.log(i);
}
// console.log(i); //Here i can't access and gives error because i has block scope. block means for loop only

Now Function scope:

let globalVar = 2023;
function myFunTrail(cY) {
  console.log(cY); //This is function scope so printing
  console.log(globalVar); //This is global scope so printing
  if (2 > 1) {
    let tempVar = 100;
    console.log(tempVar); //This is block scope so printing
  }
  // console.log(tempVar); //This is block scope and printing outside of block so error.
}
myFunTrail(2021);
// console.log(cY); //This is functions scope and printing out side of functions error. ncaught ReferenceError: cY is not defined
console.log(globalVar); //This is global scope so prining

Strict Equality operator

let numOne = 11;
let numTwo = '11';
if (numOne == numTwo) {
  console.log('This is not strict equality operator');
}
if (numOne === numTwo) {
  console.log('Not goes here');
} else {
  console.log('This is strict operator');
}

Type Coercion(auto) & Type conversion(manual)

let myAry = ['Dilip', 1984, 2022, 'Prithvi', 'Kuki'];
myAry.forEach(element => {
  let tempele = element + 2022; //Check this. JS engine automatically considore element as Number for 2 & 3. This is automatic - called type coercion. While we manually convert type using String or Number method is called type conversion
  console.log(tempele);
});

Switch statement:

The switch is actually a replacement of multiple else if.

function trySwitch(curDay) {
  switch (curDay) {
    case 'Monday':
    case 'Tuesday':
      console.log('Working day');
      break;
    case 'Saturday':
    case 'Sunday':
      console.log('Enjoy your day');
      break;
    default:
      console.log('No Data found');
      break;
  }
}
trySwitch('Sunday');

Ternary operator (condition) ? True : False

function tryTurnary(curDay) {
  if (curDay == 'Monday' || curDay == 'Tuesday') {
    console.log(`Work hard to make a great ${curDay}`);
  } else {
    console.log('Enjoy your off day!');
  }
}

tryTurnary('Monday');

To make the above code simpler we can write this.

function tryTurnary(curDay) {
  curDay == 'Monday' || curDay == 'Tuesday'
    ? console.log(`Work hard to make a great ${curDay}`)
    : console.log('Enjoy your off day!');
}

tryTurnary('Tuesday');

Function in JavaScript

When the function is going to declare as the variable it is called a Function as an expression. Now this function can’t call before declaration as it is stored in a variable. In JS variable can’t call before declaring/defining it. This gives the error Uncaught ReferenceError: Cannot access ‘myFunOne’ before initialization

let myFunOne = function (myData) {
  console.log(myData + 20);
};

A simple function can call before declaration like

console.log(mySimpleFun(200));
function mySimpleFun(myData) {
  let resutlOne = myData + 100;
  return resutlOne;
}

let’s create an arrow function. Arrow function where we omit the curly brackets(for single line fun only), function keyword, and return statement(for single line fun only).

The multiline arrow function has curly brackets & return statements.

let arrowFun = myData => myData + 500;
console.log(arrowFun(200));

Array

let myAry = [];
myAry.push(12);
myAry.push(13);
myAry.push(14);
myAry.pop();
myAry.shift();
myAry.unshift(11);

console.log(myAry);

Object

let firstObj = {
  myName: 'Dilip',
  mySurname: 'Parmar',
  mySalary: 200000,
  // if we want to use arrrow function, we cant as this is not supported by arrow function in js
  myIn: function (myData) {
    return this.mySalary + myData;
  },
};

console.log(firstObj);
console.log(firstObj.mySalary);
let realInt = firstObj.myIn(5000000);
console.log(realInt);

Loops:

When we don’t know how many repetitions we need, use the while loop else you can use for loop.

For example, rolling a dice till we get 6 – This is a while loop because we don’t know when 6 comes.

Random number in JS

// Generate random number
let randomNum = Math.trunc(Math.random() * 6) + 1;

while (randomNum !== 6) {
   randomNum = Math.trunc(Math.random() * 6) + 1;
   console.log(randomNum);
   randomNum == 6 ? console.log('Loop is about to end') : console.log(`You got ${randomNum}`);
 }

this in JS: this points to the current object

const myObj = {
  name: 'Dilip',
  birthYear: 1984,
  age: currentYear => currentYear - this.birthYear, //This keyword not work on arrow function so create function expression
  age2: function (currentYear) {
    return currentYear - this.birthYear;
  },
};

Falsy Values: There are 5 falsy values=>> 0, undefined, null, NaN, ”

let myFalsy = NaN;
if (myFalsy)
  console.log(
    `You are in if condistion means value is true. Which will not be case in case of falsy values`
  );

The next topics are: From Chapters 101 to 114

Destructing or object & array – When you want to assign an array element as a separate variable or an object property as a separate variable, we use this.


The spread operator […] or {…} – Simply spread the values of iterable (array, string)

The rest operator […] when used on the left side to assign a variable to all rest of the elements


Short-circuiting with || – return first truthy value or last one

Short-circuiting with && – return first falsy value or last one

Short-circuiting: || return first truthy value, if not found return last one. && return first falsy value, if not found return last one

Short-circuiting with ?? – return fist Nullish value ( only 2 Nullish values – null & undefined)


Logical assignment operator ||=, &&=, ??=

&&= When the value of the left operator is THRUTY then the right value is assigned to it

let bb = 10;
console.log((bb &&= 200)); //Output 200

||= When the value of the left operator is FALSY then the right value is assigned to it

let bbb;//this is undefined as falsy value
console.log((bbb |= 500)); //output is 500

??= When the value of the left operator is NULLISH then the right value is assigned to it

let ccc = null;
console.log((ccc ??= 700));

Optional chaining operator ?. ,?() – useful when working with JSON structure

?. use to check if the object property is set or not. if not then set

?() use to check if the function exists or not


For.. of in loop in array

For.. in the loop in object


object.keys()

object.values()

object.entries()