Skip to main content

JS basics

JS in layman terms, its was a scripting language developed to be used on the browser to work with html elements and engage with the backend. But it is adopted in almost all the layers.

Basic sample code

As JS works on html elements we need a html file index.html and let have javascript in a separate file as index.js. This js file is imported into the html file and browser render the html and executes the js file in its javascript execution context. Both the files should be in the same folder as of now.

JS is a Synchronous single thread language. There will be a single execution context within this all the sub execution context's are controlled and maintained by call stack

index.html
<!DOCTYPE html>
<html>
<head>
<title>SecOpsBear Play time</title>
</head>
<body>
<h1>SecOpsBear Let play</h1>

<p id="demo"></p>

<script src="index.js"></script>
</body>
</html>
index.js
const bearWorld = "This is Wonder full!";

document.getElementById("demo").innerHTML = bearWorld;
console.log("You can find me in console ctrl+shift+i");

variables let, var and const

variable can be defined using let and var. Main difference is let limits the scope of the variable defined but var can be accessed globally. And const is constant and cannot be changed in the scope of definition.

const a_const = "Hello";
{
let accessLet = "let is inside the {}'s, hence the scope";
console.log(accessLet);
var getVar = "This is var!";

console.log("accessing " + a_const);
}
// try accessing accessLet below, this should through an error
// console.log(accessLet);
console.log(getVar);

// adding const's and coercion
const num1 = 101;
const num2 = 202;
const result =
"sum is " +
num1 +
num2 +
" <-- num1 and num2 converted to string and concatenated";
console.log(result);
const result2 =
"sum is " +
(num1 + num2) +
" <-- num1 and num2 are add and then converted to string and concatenated";
console.log(result2);

const lit = `Hello!
num1 is ${num1}
num2 is ${num2}
Accessing inside literal`;
console.log(lit);

console.log(typeof lit);
output
let is inside the {}'s, hence the scope
accessing Hello
This is var!
sum is 101202 <-- num1 and num2 converted to string and concatenated
sum is 303 <-- num1 and num2 are add and then converted to string and concatenated
Hello!
num1 is 101
num2 is 202
Accessing inside literal
string

== and ===

=== (triple equal) is strict equality operator. This does not perform type coercion. Only returns true if both types are same.

== (double equal) is loose equality operator and it does type coercion.

Now you might ask what is type coercion - it means the automatic or implicit conversion of values from one data type to another. As shown below in == operation, the value of const a is of type number whereas the value of const b is of type string. Since its a double equal operator type coercion occurs and the result is TRUE.

const a = 20;
const b = "20";

console.log(a == b);
// true
console.log(a === b);
// false

switch case

const car = "toyota";
switch (car) {
case "mercedes":
console.log("mercedes car from germany!");
break;
case "bugatti":
console.log("Bugatti car!");
break;
case "toyota" || "nissan":
console.log("Nice japanese car!!");
default:
console.log("Im in default too!!!");
break;
}

conditional ternary

// check if x is greater than or equal to 10; if true return "Yeh!" else return "Nop!"
const x = 30;
x >= 10 ? console.log("Yeh!") : console.log("Nop!");

functions

basic functions

function cooking() {
console.log("Lets cook");
}

cooking();

// area function receives 2 parameters
function area(length, hight) {
const area = length * hight;
// console.log("Area is : " + area);
const data = `Area is ${area}`;
return data;
}

const areaData = area(10, 90);
console.log(areaData);

function declaration and expression

function can be declared anywhere in the script and accessed (hoisting) but in expression the function variable can be called only after it is defined.

// expression functions
const cars = function (v) {
return "This car is " + v;
};

const car = cars("Benz");

// accessing fruits before defining
const f1 = fruits("oranges");

// declaration of function fruits
function fruits(apple) {
return "apples are " + apple;
}

console.log(f1, car);

Arrow functions

This is a form of expression function and Arrow function do not get this key word.

// express function
const squareArea = function (side) {
return side * side;
};

// Arrow function - the same above function can be written
const squareArea2 = (side) => side * side;
console.log("squreAre: " + squareArea(10) + " squareArea2: " + squareArea2(20));

// Arrow function with parameters
const triangleArea = (base, hight) => {
const area = (base * hight) / 2;
return area;
};
console.log(`Area of triangle is: ${triangleArea(10, 5)}`);

Arrow function returns multiple values

// Arrow function receives parameters and returns multiple parameters
const triangleArea1 = (base, hight) => {
const area = (base * hight) / 2;
return { areaT: area, bString: "A new day" };
};

// const {areaA,stringB} = triangleArea1(10,10);
const { areaT, bString } = triangleArea1(10, 10);
console.log(`a is ${areaT} and b is ${bString}`);

Arrays

Arrays in javascript can store multiple data types

"use strict";

const animals = ["dog", "cat", "pig"];
console.log(animals);

const days = new Array("Monday", "Tuesday", "Wednesday");
console.log(days);

console.log(days[2]);
console.log("size of the array: " + days.length);

// Array elements can be updated but a new array cannot be assigned
animals[1] = "Cow";
console.log(animals);
// animals = ["eagle","parrot"] // cannot be done for const array

// In JS arrays can store multiple data types
const mutliData = ["John", 10, 99.9, 8 * 10, animals];
console.log(mutliData);

Output:
Arrays output

length of an array

const mutliData = ["John", 10, 99.9, 8 * 10, animals];
console.log(mutliData.length);

Add/Remove elements in Arrays

unshift - Add at the beginning

// Add in the beginning of array
animals.unshift("Stars");
console.log(animals);

push - Add at the last

// Add after the last element in array
animals.push("Stones");
console.log(animals);

shift - Remove the first element

// Remove the first element
animals.shift();
console.log(animals);

pop - Remove the last element

//Remove the last element
const a = animals.pop();
console.log("Removed element is: " + a);
console.log(animals);

Output:

[ 'Stars', 'dog', 'Cow', 'pig' ]
[ 'Stars', 'dog', 'Cow', 'pig', 'Stones' ]
[ 'dog', 'Cow', 'pig', 'Stones' ]
Removed element is: Stones
[ 'dog', 'Cow', 'pig' ]

includes - check element exists in array

includes returns true if exists and false if it doesn't. No Coercion - it is strict check

console.log(animals.includes("Cow"));
// true

indexOf - get the position of element

console.log(animals.indexOf("pig"));
// 2

Objects

Object properties can be accessed through dot notation or brackets [] - "Computed Member Access"

"use strict";

const Employee = {
firstName: "Sam",
lastName: "Jack",
age: 10,
pets: ["dog", "cat", "pig"],
};

console.log(typeof Employee);
console.log(Employee.firstName);

const keyValues = "Name";
console.log(Employee["first" + keyValues]);

const check = prompt("Enter name or age");
console.log(Employee[check]);

Object methods

use this operator to access the property within the object.

"use strict";

const sam = {
firstName: "Sam",
lastName: "Jack",
age: 10,
salary: function (v) {
return v * this.age;
},
};

// dot notation - to accessing the property
console.log(sam.firstName);
// bracket notations - to access the property, here we can compute an expression to get the property name
const keyName = "Name";
console.log(sam["first" + keyName]);

console.log(sam.salary(10));
console.log(sam["salary"](2000));

New property created inside method

The new property created after calling the salary method is newData and it is accessed as a regular object property.

const sam2 = {
firstName: "Sam",
lastName: "Jack",
age: 10,
salary: function (v) {
this.newData = v * this.age;
return this.newData;
},
};

console.log(sam2.salary(1000));
console.log(sam2.newData);

for loop

const people = ["sam", "john", "jack", "king"];
for (let index = 0; index < people.length; index++) {
const element = people[index];
console.log(element);
}

continue the loop (skip)

When the if condition is true the statements below are skipped, the index increments and loop continues

// using continue and break
// print only odd numbers
for (let index = 0; index < 10; index++) {
if (index % 2 === 0) continue; // when its true the statements below are not executed
console.log(index);
}

break the loop

for (let index = 1; index < 10; index++) {
if (index % 7 === 0) break; // exits the loop when true
console.log(index);
}
// prints till 6 and exits

while loop

const people = ["sam", "john", "jack", "king"];
let x = 0;
while (x < people.length) {
const element = people[x];
console.log(element);
x++;
}

falsy values

falsy values are the values that are evaluated to the false boolean value and there are 6 such values.

  1. false
  2. 0
  3. '' or "" - empty string
  4. null
  5. undefined
  6. NaN - Not a Number

&& - || - ??

&& is the AND logic, if any of the variable is false then it resolves to false

|| is the OR logic, if any of the variable is true then it resolve to true

?? if value is null or undefined then executes the statement

let a;
const x = a ?? 10; // since 'a' is undefined, 10 is assigned to x

a = 9;
const p = a ?? 10; // now 9 is assigned to 'p' since 'a' is not undefined