JS Basics: Important Concepts of JavaScripticon

JAVASCRIPT, NOT "JAVA"

What is JS?

JS is a scripting (programming) language that allows you to dynamically create/update content of your webpage.

JS is very different from JAVA programming language. JAVA is Object Oriented Programming language where as JavaScript is a Scripting language. Never get confused between them, they are completely different things.

JS is dynamically typed programming language.

Variables & Data Type

Variables

A variable is a named storage location in a computer's memory that holds a value. It acts as a container for data that can be referenced and manipulated throughtout a program's execution.

let x = 10; // defining a variable "x" and assigning value to it.

x = x + 10; // updating the value of "x" by adding 10.

A variable can be defined using any of the following keywords:

  • var: Creates a variable whose value can be changed. It was used in older version of JS, should be avoided.
  • let: Creates a variable whose value can be changed. It is the morder way to define a variable.
  • const: Creates a variable whose value cannot be changed

Variable name cannot be a keyword.

Data Types

While dealing with data, your computer needs to know the type of data it is dealing with.

Some Common data types are:

  • Numbers: integer (30, -40, 50), decimals (19.11, 7.9)
  • Strings: "Hello World", "s", "Strings can be as long as you like"
  • Booleans: True or False

What can we store in variable

Values that can be stored in a variable can be categorized into 2 categories

  • Simple Value: Like integer, String or Booleans
  • Reference: An address to something else, like an Array, Object or Function

Functions and Control Flow

Functions

Functions are self-contained block of code designed to perform a specific task

Functions allows you to define a piece of code once and then execute it multiple times throughout your program by "calling" the function, avoiding code duplication (DRY - Don't Repeat Yourself principle).

Functions can accept input values, known as parameters.

Functions are defined by using "function" keyword.

/* Syntax to define a function */

function <Function Name>(parameter list) {

// Function body

}

Function name cannot be a keyword.

Function can accept zero or more parameters.

Functions can return values.

In JavaScript, "{}" are very important, they define the scope of function or code block (like if-else, loops, try-catch, etc).

/* Function with paramters */

function greet(name) {

  console.log(`Hello, ${name} !!`)

}

/* Function without paramters */

function greet() {

  console.log(`Hello, good morning!)

}

/* Function returning a value */

function getSquare(num) {

  let sq = num * num;

  return sq;

}

Control Flow

While writing code, many time we have to execute different code based on some condition, parameter, response, error code, etc.

Control flow in programming refers to the order in which a computer executes the statements and instructions within a program.

By default, code typically executes sequentially from the first line to the last.

However, control flow structures allow programmers to alter this default order, enabling programs to make decisions, repeat actions, and handle different scenarios.

Conditional Statement:

if-else:

Let execute one code block if the condition is true and other if condition is false

if(num % 3 === 0) {

  // condition is true

  console.log("Number is divisible by 3");

} else {

  // condition is false

  console.log("Number is not divisible by 3");

}

else-if:

It allows you to chain multiple if-else block.

if(num % 3 === 0) {

  // first condition is true

  console.log("Number is divisible by 3");

} else if(num % 5 === 0) {

  // second condition is true

  console.log("Number is divisible by 5");

} else if(num % 7 === 0) {

  // third condition is true

  console.log("Number is divisible by 7");

} else {

  // none of the condition is true

  console.log("Number is not divisible by 3,5 or 7.");

}

Compilier will start testing from first condition and keep checking the if conditions until it finds a true condition, and execute the code block for that condition.

Once a true condition is found, compilier will skip all other if conditions and else block

If none of the if condition is true then else block will be executed.

Else block is not mandatory.

switch-case:

Provides a way to execute different blocks of code based on the value of a single variable or expression.

switch(expr) {

 case "Sunday":

  console.log("yay!!");

  break;

 case "Saturday":

  console.log("party!!!");

  break;

 case "Monday":

 case "Tuesday":

 case "Wednesday":

 case "Thursday":

  console.log("Ohh Noooooo!!!");

  break;

 case "Friday":

  console.log("Almost there!!!");

  break;

 default:

  console.log("Invalid day");

}

for-loop:

Iterate over a sequence (like a list or array) for a specific number of times.

// for-loop syntax

for(initialize looping variable; Termination condition; increment/decrement) {

 // code block you want to repeat

}

// for-loop to print the multiplication table of 7

for(let i=1; i < 11; i++) {

 console.log(`7 times ${i} = ${7*i}`);

}

Arrays & Objects

Array

An array is a single variable used to store an ordered collection of multiple values.

These values, known as elements, can be of any data type (numbers, strings, booleans, objects, or even other arrays).

Each element in an array is assigned a numeric index, starting from 0 for the first element

Elements are accessed using these indices enclosed in square brackets (e.g., myArray[0]).

Arrays can be created using square brackets []

const fruits = ["Apple", "Banana", "Orange"]; // Array of String

const number = [11, 45, -31, 0, 99, 10000, -10000]; // Array of Numbers

const objects = [{}, {}, {}, {}];// Array of Objects

Practise:

Create an array of your favorite colors.

Add (push) a new color to the end.

Remove (pop) the last color.

Loop through the array and print each color.

Objects

Objects are used to store collection of related data(property) and functionality(behaviour).

Unordered collections of key-value pairs.

Objects can be created using { }

// Person Object with some properties(data) and a behaviour(function)

const person = {

 name="John";

 age=37;

 email="John@hotmail.com";

 function greet() {

  console.log("John says HI!!!");

 }

}

Object properties can be access using dot(.) notation (eg: person.name)

JSON: JavaScript Object Notation, is a very popular formate for sending/receiving data from an API.

Practise:

Create an object representing a book (title, author, pages, isRead).

Access and print the book's title and author.

Change the isRead status

Run

Output

</>