JavaScript For LWC | Basics Concepts for beginners

JavaScript, one of the fastest growing programming languages. It is a lightweight, cross-platform, single-threaded, and interpreted compiled programming language. It is also known as the scripting language for webpages, used to create dynamic and interactive elements in web applications.

It is easy to learn. It is another useful skill to bag, if your are on your way of becoming a better developer (even in a non-salesforce way).

It was initially used to create interactive webpages in browsers. Owing to community support and investments, you can now build fully blown both web and mobile applications, real-time networking applications and even games using Javascript.

JavaScript was originally designed to run on browsers having inbuilt JavaScript engines, but owing to a smart engineer we now have nodes. Using an open sourced JavaScript engine in chrome, he embedded it inside C++ program to create a Node. Now, both browsers and Nodes can be used a run time environment for JavaScript execution.

Some popular editors for JavaScript would be Visual Studio Code (VSCode), Sublime Text, Atom, etc.

Setup VSCode

We would be working with VSCode setup during our concepts. Create a New folder and drag in on to your vscode app. Go to open editors and create a new file named ‘index.html’. On the file, type an exclamation(!) and press Enter/Tab and your basic HTML boiler plate and go ahead and save the changes.

Install Live Server Extension on VSCode

Javascript in LWC
Open HTML file with Live server

We will use this webserver to serve our web application. Install and restart the VSCode. We can now open our saved html file with Live server as below, and any changes saved would reflect real time on the webpage as below.

Adding scripts to the html file

We can put our scripts ahead after both <head> and <body> tag. But as of best practice we put our scripts(codes) after the body so as to not keep the browser occupied running the scripts before it displays the body of the page. As JavaScript is an interpreted language that executes code line by line providing more flexibility.

JavaScript contains a standard library of objects like Array, Date, and Math and a core set of language elements like operators, control structures and statements. 

Variables and Datatypes in JavaScript

Variables are the building blocks for storing and manipulating information within a program. Javascript is a dynamically or loosely typed language, meaning the type of a variable can change at run time.

Variables are categorically of two types.

  1. Primitive or Predefined or In-built Data Types: The 7 primitive data types are String(sequence of characters), Number(integers and decimals), Boolean, Undefined(unassigned), Null(empty value), Symbol(unique and unchanged), BigInt(larger integers than number can hold).
  2. Non-Primitive or Reference or Derived Data Types: These are Object, Array and Function

Objects

Objects in programming languages are used to store multiple related variables as for instance a person has attributes like name, age city etc. So these attributes are a part of the representation of a person.

// Defining an object in JavaScript
const person = {
   name : 'Rajat',
   age : 20,
   city : 'Agra'
};

// Dot Notation
person.name = 'Madan';

// Bracket Notation, can be used to pass attribute dynamically
person['name'] = 'Vijay';

console.log(person.name); 
// output 'Vijay'

Arrays

Technically arrays are just objects, storing data within square brackets[] and inherit some properties like forEach, keys, fill, every, length, etc.

let class = ['Raja' , 'Ram', 'Mohan', 'Roy'];
console.log(class.length);

// output is 4

Here the indexing starts from 0, being the first element ‘Raja’.

Functions

Functions are a set of statement that performs a task or calculates a output value.

//defining a function

function sayHello() {
    console.log('hello');
}

function addNum(num1,num2){
   return num1+num2;
}

//calling a function

sayHello();
let number = addNum(2,1);

Variables can be created/declared using var, let and const keywords.

Declaring Variables using var, let, and const

Var Keyword

Var keyword is used to declare a function or globally scoped variable.

Let Keyword

Let keyword is a block-scoped (enclosed by curly braces `{}`) variables commonly used for variables that may change their value.

Const Keyword

Const keyword declares constant variables that cannot be reassigned. It is block-scoped as well.

//number literal
var age = 10;
const a = 5;

//String literal
let name = 'Mohan';

//boolean
var isFlag = true;

Global and Local variables in JavaScript

Global variables in JavaScript are those variables that are accessible from anywhere within the script, including inside functions and blocks. These are declared outside of any scope or function.

Local variables in JavaScript are those confined to the scope of the function that defines them and cannot be accessed from outside. These are defined within functions in JavaScript.

Operators in JavaScript

Arithmetic Operators

  1. Add (+)
  2. Substract (-)
  3. Multiply (*)
  4. Divide (/)
  5. Remainder (%)
  6. Exponential (**)
  7. Increment (++)
  8. Decrement (–)

An interesting thing about the increment and decrement operators here is that based on whether it is placed before and after the variable, the value is incremented/decremented after or before the execution of the expression.

x=1;
console.log(++x);
// output is 2

console.log(x++);
// output is 1 but the value is changed to 2 afterwards

Assignment Operators

x= x+5; 

//can be written as 

x+=5;

Similarly all the arithmetic operators can we have a similar combination.
x-=5 i.e. x = x-5
x*=5 i.e. x = x*5
x/=5 i.e. x = x/5, etc.

Comparison Operators

Relational Operators :

  1. Greater than (>)
  2. Less than (<)
  3. Greater than or Equal to (>=)
  4. Less than or Equal to (<=)

Equality Operators :

  1. Equals to (===) is a strict equality operator that requires same type as well as value. Example : ‘1’ === 1 is false
  2. Equals to (==) is a loose equality operator that requires only the value. Example : true ==1 is true
  3. Not equals to (!==)

Ternary or Conditional Operators

Ternary Operator works similar to conditional if-else statements. It is based on a condition, a value to return if the condition is true, and a value to return if the condition is false.
Syntax being: (condition ? trueExpression : falseExpression)

let x = 10;
let result = (x > 0) ? true : false;

Logical Operators

Logical operator with booleans:

  1. And (&&)
  2. Or (||)
  3. Not(!)

Logical operator with non-booleans: They return one of the original values instead of a boolean. For &&, if the first operand is false, it returns the first operand. Otherwise, it returns the second operand. While for ||, if the first operand is truthy, it returns the first operand; otherwise, it returns the second operand.

false && true —–> false
false || true ——-> true

Other examples :

false || ‘Ram’ ——> ‘Ram’
false || 1 ————> 1
false || 1 || 2 ——-> 1 , if first operant is false then second is true irrespective of other operands.

let userSelection = 'apple';
let defaultSelection = 'banana';

// output is userSelection, when it has some value like here Apple.

let servedFruit = userSelection || defaultSelection;
console.log(servedFruit);

let userSelection = undefined;

// output is defaultSelection, when it has no value

console.log(servedFruit);

Bitwise Operator

We transform the operation to a bitwise format and operate and then transform back the results. We don’t need to discuss depths of this but you can check this here.

Control Flow in JavaScript

1. Conditional Statements

If-Else:

let score = 63;
 
if (score >= 90) {
  console.log('You've got an A!');
} else if (score >= 80) {
  console.log('You've got a B.');
} else {
  console.log('You've got a C ,.');
}

Switch Case

let fruit;

switch(fruit){
   fruit 'red' : 
      console.log(' Fruit was red ');
      break;

   fruit 'green' : 
      console.log(' Fruit was green ');
      break;

   fruit 'yellow' : 
      console.log(' Fruit was yellow ');
      break;

   default :
      console.log(' Fruit is brown ');
}

2. Loop Statements

For

for( i = 0; i<5; i++){ 
   console.log('i'); 
}

// output will be: 0,1,2,3,4 

For above, the loop will execute as long as the condition (i<5) is true and after each iteration we have an i incremented.

While

Above conditional logic can also be achieved using ‘while’ loop as under.

let i=0;
while(i<5){
  console.log(i);
   i++;
}

In similar fashion the above is executed while condition(i<5) is true and during each iteration the value is incremented by 1.

Do -While

Similar to the above ‘while’ loop, do-while is executed for as long as the condition is true. The only difference being is that even if the condition is not met it would be at least executed once.

let i=0;
do{
   console.log(i);
   i++;
}
while(i<5);

The reason being the do part comes before the condition being evaluated so it is at least executed once and if the condition is not fulfilled the loop then after gets terminated.

For-in

let employee = {
  name: 'Rahul',
  age: 32,
  city: 'kanpur',
  dept: 'IT'
};

for(let key in employee){
  console.log(key, employee[key]);
}

For instances we are using arrays where we don’t have keys, we have index.

For-of

const fruits = ['apple', 'pear', 'grapes'];

for(let fruit of fruits){
  console.log(fruit);
}

Break and continue

As the name suggests, break is used to break out of the loop while continue is to jump at the beginning of the loop and continue the execution of next iteration.

let i=0;
while(i<=100){

//when i=3, i is incremented to 4 and the execution jumps to next iteration and skips below code
 if(i===3){
  i++;
    continue;
  }

//when i =10, the loop is exited and no more execution happens
if(i==10){
  break;
}
 
  console.log(i);
  i++;
}


\\Output
0,1,2,4,5,6,7,8,9

More about Objects in JavaScript

Objects not only store related variables but they can also store another object, and even functions.

const square = {
  side: 1,
  location: {
      x:1,
      y:1
   },
  isFillColor: true,
  move: function() {
     console.log('Moving the square');
   }
  };

//call the function-->method
square.move();

The above can be referred as Object Oriented Programming System or (OOPs). It is a style of programming based on the concept of objects, which can contain both data and code.

Factory Functions in JavaScript

A factory function in JavaScript is a function that creates and returns objects in a more controlled and customizable manner.

Factory Functions come into picture when we want to have avoid redundancy in our code. Rather than instantiating object records from scratch each time we can reuse the code to create and return instances of the object.

function createSquare(side){
   return {
//same as writing, side: side, as key value pair is same
     side,

// for, move: function() we can drop the function keyword inside an object
     move(){
     console.log('Moving the square');
      }
   };
}

//call the function to instantiate the object
const sq1 = createSquare(1);
     

Constructor Functions in JavaScript

Constructor functions in JavaScript is used to create an object type to create multiple objects of the same type. Similar to the factory function it is used to initialize instances of an object, its just another approach to it.

Contrary to above, constructor does not need to return the object, but uses ‘new’ and ‘this’ keyword.

function Square(side){
   this.side = side;
   this.move = function() {
        console.log('move');
    }
}

const square = new Square(1);

While naming methods and instances we generally use Camel Notation, i.e. first letter of the word being in lowercase and rest in Uppercase(camelNotation). We use Pascal Notation, i.e. every first letter is uppercase(PascalNotation) for naming constructor functions. Every object has a constructor property, that is the function used to create the object.

It is imperial to note that these objects in JavaScript are dynamic in nature. We can always add or delete properties as below:

const square ={
 radius:1
}

//add property
square.fillColor = true;

//delete property
delete square.fillColor;

Constructor Property of Objects in JavaScript

Every object has a constructor property that references a function that was used to create the object. We can type object.constructor on the console to inspect the function

square.contructor
// output:
 f Square (side){
   this.side = side;
   this.move = function() {
        console.log('move');
    }
}

But for below instance ‘a’, it also has a constructor function internally in Javascript.

let a = '';
//translates as: let a = new Object (); 

Functions as Objects in JavaScript

Functions in JavaScript are also Objects as they have in-built methods and properties, besides those being assigned to them. The standard built-in Function is the object upon which functions are based. The built-in Function object has properties like namelength, caller, prototype  and has methods like callapply and bind.

1 thought on “JavaScript For LWC | Basics Concepts for beginners”

Leave a Reply

error: Content is protected !!