Summary:👉 TABLE OF CONTENTS:
- Chapter 01: Variables
- Chapter 02: Operators
- Chapter 03: Data Types
- Chapter 04: Functions
- Chapter 05: Global Functions
- Chapter 06: Loops
- Chapter 07: If- else
- Chapter 08: Switch Statement
- Chapter 09: Arrays
- Chapter 10: JSON j
- Chapter 11: Promises
- Chapter 12: Helpful Codes
JavaScript is a programming language that powers the dynamic behavior on most websites. In this article, we are focusing on the basic JAVASCRIPT code patterns. So, JAVASCRIPT is most suitable for beginner developers who have basic experience in any programming language.
INTRODUCTION TO BASIC
Variables ✅
- Variables are containers for storing data values.
- Uses reserved keyword var to declare a variable.
var a; // variable
var b = "hello"; // string
var c = "Hi" + " " + "Danu"; // = "Hi Danu"
var d = 2 + 2 + "3"; // = "43"
var e = [4, 6, 7, 9]; // array
var f = true; // boolean
var g = function () { }; // function object
var a = 5, b = 2, c = a + b; // one line
const PI = 3.14; // constant
let z = 'xxx'; // block scope local variable
Operators ✅
- Performs some operations on single or multiple operands(data value) and produces a result.
- JavaScript supports the following types of operators.
- Arithmetic Operators
- Logical Operators
- Comparison Operators
- Conditional Operators
- Assignment Operators
a = b + c - d; // addition, substraction
a = b * (c / d); // multiplication, division
x = 100 % 48; // modulo. 100 / 48 remainder = 4
a++; b--; // postfix increment and decrement
a * (b + c) // grouping
person.age // member
person[age] // member
!(a == b) // logical not
a != b // not equal
typeof a // type (number, object, function...)
x << 2; x >> 3 // minary shifting
a = b // assignment
a == b // equals
a === b // strict equal
a != b // unequal
a !== b // strict unequal
a < b; a > b // less and greater than
a <= b; a >= b // less or equal, greater or eq
a += b // a = a + b (works with - * %...)
a && b // logical and
a || b // logical or
Data Types ✅
- There are two types of Data Types.
- Primitive Data Type
- String
- Boolean
- Number
- Null
- Undefined
- Non-primitive Data Type
var age = 18; // number
var name = "Tom"; // string
var fullName = { first: "Tom", last: "Doe" }; // object
var truth = true; // boolean
var sheets = ["HTML", "CSS", "JS"]; // array
var a; typeof a; // undefined
var x = null; // value null
Functions ✅
- JavaScript function can be defined using the function keyword.
function addNumbers(a, b) {
return a + b;;
}
x = addNumbers(1, 2);
Global Functions ✅
eval(); // executes a string as if it was script code
String(10); // return string from number
(10).toString(); // return string from number
Number("10"); // return number from string
encodeURI(uri); // encode URI. Result: "my%page.asp"
decodeURI(enc); // decode URI. Result: "my page.asp"
encodeURIComponent(uri); // encode a URI component
decodeURIComponent(enc); // decode a URI component
isFinite(); // is variable a finite, legal number
isNaN(); // is variable an illegal number
parseInt(); // parses a string and returns an integer
parseFloat(); // returns floating point number of string
Loops ✅
✔ For Loop
- For loop requires the following 3 parts.
- Initializer - Initialize our counter to a starting value
- condition - Specify a condition that must evaluate to true for the next iteration
- Iteration - increase or decrease the counter
for (var i = 0; i < 10; i++) {
document.write(i + ": " + i * 3 + "<br />");
}
var sum = 0;
for (var i = 0; i < a.length; i++) {
sum += a[i];
}
html = "";
for (var i of custOrder) {
html += "<li>" + i + "</li>";
}
✔ While Loop
- Only requires condition expression.
- The purpose of a while loop is to execute a statement or code block repeatedly as long as an expression is true.
var i = 1; // initialize
while (i < 100) { // enters the cycle if statement is true
i *= 2; // increment to avoid infinite loop
document.write(i + ", "); // output
}
////----Do-while Loop----////
var i = 1; // initialize
do { // enters cycle at least once
i *= 2; // increment to avoid infinite loop
document.write(i + ", "); // output
} while (i < 100) // repeats cycle if statement is true at the end
✔ Break & Continue
- Break statement "jumps out" of a loop.
- Continue statement "jumps over" one iteration in the loop.
////----Break----////
for (var i = 0; i < 10; i++) {
if (i == 5) {
break; // stops and exits the cycle
}
document.write(i + ", "); // last output number is 4
}
////----Continue----////
for (var i = 0; i < 10; i++) {
if (i == 5) {
continue; // skips the rest of the cycle
}
document.write(i + ", "); // skips 5
}
If - else ✅
- The 'If - else' statement is the next form of control statement that allows JavaScript to execute statements in a more controlled way.
if ((age >= 16) && (age < 19)) { // logical condition
status = "Eligible."; // executed if condition is true
} else { // else block is optional
status = "Not eligible."; // executed if condition is false
}
Switch Statement ✅
- The switch statement is useful when we want to execute one of the multiple code blocks based on the return value of a specified expression.
switch (new Date().getDay()) { // input is current day
case 1: // if (day == 1)
text = "Monday";
break;
case 0: // if (day == 0)
text = "Sunday";
break;
default: // else...
text = "Something";
}
Arrays ✅
- An array in JavaScript can be defined and initialized in two ways, Array literal and Array constructor syntax.
✔ Array Literal
- It takes a list of values separated by a comma and enclosed in square brackets.
var stringArray = ["one", "two", "three"];
var numericArray = [1, 2, 3, 4];
var decimalArray = [1.1, 1.2, 1.3];
✔ Array Constructor
- Initialize an array with Array constructor syntax using a new keyword.
var stringArray = new Array();
stringArray[0] = "one";
stringArray[1] = "two";
var numericArray = new Array(3);
numericArray[0] = 1;
numericArray[1] = 2;
JSON j ✅
- JSON - JavaScript Object Notation
- JSON is a syntax for storing and exchanging data.
- JSON is a text format that is completely language-independent.
var str = '{"names":[' + // crate JSON object
'{"first":"Don","lastN":"Jon" },' +
'{"first":"John","lastN":"Lewis" },' +
'{"first":"King","last":"Jordan" }]}';
obj = JSON.parse(str); // parse
document.write(obj.names[1].first); // access
////----Sending Data----////
var myObj = { "name": "Danuka", "age": 23, "city": "Sri Lanka" }; // create object
var myJSON = JSON.stringify(myObj); // stringify
window.location = "demo.php?x=" + myJSON; // send to php
////----Storing Data and retrieving Data----////
myObj = { "name": "Danuka", "age": 23, "city": "Sri Lanka" };
myJSON = JSON.stringify(myObj); // storing data
localStorage.setItem("testJSON", myJSON);
text = localStorage.getItem("testJSON"); // retrieving data
obj = JSON.parse(text);
document.write(obj.name);
Promises ✅
- Contains both the producing code and calls to the consuming code.
- A Promise may be a proxy for a value not necessarily known when the promise is created. It allows you to associate handlers with an asynchronous action's eventual success value or failure reason.
- A Promise Object can be :
- Pending:: Result - Undefined
- Fulfilled:: Result - a result value
- Rejected:: Result - an error object
function sum(x, y) {
return Promise(function (resolve, reject) {
setTimeout(function () { // send the response after 1 second
if (typeof x !== "number" || typeof y !== "number") { // testing input types
return reject(new TypeError("must to be numbers"));
}
resolve(x + y);
}, 3000);
});
}
var myPromise = sum(5, 5);
myPromise.then(function (result) {
document.write(" 5 + 5: ", result);
return sum(null, "num"); // Invalid data and return another promise
}).then(function () { // Won't be called because of the error
}).catch(function (err) { // The catch handler is called instead, after another second
console.error(err); // => Please provide two numbers to sum.
});
✅ Now I think you are got an idea about JavaSCript coding. So, we will see in the next article.✋✋
👉👉Helpful Codes👇👇
✔outputs
console.log(x); // write to the browser console
document.write(x); // write to the HTML
alert(x); // output in an alert box
confirm("Hello"); // yes/no dialog, returns true/false depending on user click
prompt("Your age?", "0"); // input dialog. Second argument is the initial value
✔Objects
var student = { // object name
firstName: "Danuka", // list of properties and values
lastName: "Dilshan",
age: 23,
height: 185,
fullName: function () { // object function
return this.firstName + " " + this.lastName;
}
};
student.age = 25; // setting value
student[age]++; // incrementing
name = student.fullName(); // call object function
✔Methods
x.toString(); // convert to string: results "Bulldog,Beagle,Labrador"
x.join(" * "); // join: "Bulldog * Beagle * Labrador"
x.pop(); // remove last element
x.push("Something"); // add new element to the end
x[x.length] = "Something"; // the same as push
x.shift(); // remove first element
x.unshift("Something"); // add new element to the beginning
delete x[0]; // change element to undefined (not recommended)
x.splice(2, 0, "y", "z"); // add elements (where, how many to remove, element list)
var animals = x.concat(cats, birds); // join two arrays (dogs followed by cats and birds)
x.slice(1, 4); // elements from [1] to [4-1]
x.sort(); // sort string alphabetically
x.reverse(); // sort string in descending order
x.sort(function (a, b) { return a - b }); // numeric sort
x.sort(function (a, b) { return b - a }); // numeric descending sort
highest = x[0]; // first item in sorted array is the lowest (or highest) value
x.sort(function (a, b) { return 0.5 - Math.random() }); // random order sort