JavaScript Basic Concept
String, Number, and Array
<h2>My First JavaScript</h2>
<button type="button"
onclick="document.getElementById('demo').innerHTML = 'Hello Reader'">
Click me to display Date and Time.</button>
<p id="demo"></p>
JavaScript is a lightweight, interpreted, or just-in-time compiled programming language.
One of the most popular programming languages for web development.
It was mainly used for the front-end only. Nowadays backend development is super easy by using Node.
Anyway, we have to learn the basics of Javascript. Let's go for String, Number, and Array.
String :
JavaScript strings are used for storing and manipulating text. a string is zero or more characters written inside single or double-quotes.
Example :
var x = "Khalid mahfuz";
var x = 'Khalid mahfuz';
var x = "Khalid m's mahfuz";
String Property :
String Length: use the built-in length property to get the length of the string.
<p id="demo"></p><script>
var txt = "ABCDEFGHIJKLMNOPQRSTUVWXYZ";
var strLen = txt.length;
document.getElementById("demo").innerHTML = strLen;
</script>Output will be : 26
String Methods:
indexOf(), lastIndexOf(), search(), slice(start,end),substring(start,end), substr(start,length), replace(old,new), concat(), trim().
indexOf()
We will use indexOf() method to find a string in a string. It will return the index of the first occurrence of a given string.
<p id="demo"></p>
<script>
let str = "Please find where find occurs!";
let pos = str.indexOf("find");
document.getElementById("demo").innerHTML = pos;
</script>Output:
7
lastIndexOf()
It will return the index of the last occurrence of a given string.
<p id="demo"></p>
<script>
let str = "Please find where find occurs!";
let pos = str.lastIndexOf("find");
document.getElementById("demo").innerHTML = pos;
</script>Output:
18
Note: if no match found, both indexOf() and lastIndexOf() will return -1.
Quiz: search() and indexOf() will return the same result. But there are 2 differences. What are they?
Ans: 1. search() can take regular expression as argument, indexOf() cannot. 2. search() cannot take 2nd argument, indexOf()/lastOndexOf() can take 2nd argument as the starting position for the find.
Extracting string parts:
There are 3 useful methods for extracting a part of a string/text.
- slice(start,end)
- substring(start,end)
- substr(start,length)
slice()
slice() method extracts a desired part of a string and returns the extracted part in a new string. We will pass 2 parameters: start position and end position(end excluded).
<p id="demo"></p>
<script>
let str = "01apple78ban23a5kiw90";
let res = str.slice(7,13);
document.getElementById("demo").innerHTML = res;
</script>Output:(N.B: position 7 to 12 not 13)
78ban2
Note: if the parameter is negative, the position is counted from the end of the string.
<p id="demo"></p>
<script>
let str = "01apple78ban23a5kiw90";
let res = str.slice(-7,-4);
document.getElementById("demo").innerHTML = res;
</script>Output:
a5k
substring()
same as slice() method. but substring() cannot take negative indexes.
substr()
substr() method is same as slice() method. but substr()’s 2nd parameter is length, not position.
<p id="demo"></p><script>
let str = "01apple78ban23a5kiw90";
let res = str.substr(7,13);
document.getElementById("demo").innerHTML = res;
</script>Output:
78ban23a5kiw9
replace()
replace() method replaces a specified value in a string with another given value. It doesn't change the old string. It returns a new string.
<button onclick="myFunction()">Change a word</button><p id="demo">Please visit Yahoo</p><script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace("Yahoo","Google");
document.getElementById("demo").innerHTML = txt;
}
</script>Output:
Please visit Google
replace() method replaces only the first match and this is case sensitive. For example, it can not replace uppercase with lowercase.
So to replace case insensitive, we need to use regular expression with an /i flag.
<button onclick="myFunction()">Try it</button><p id="demo">Please visit Yahoo</p><script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/YaHoO/i,"Goole");
document.getElementById("demo").innerHTML = txt;
}
</script>Output:
Please visit Google
And to replace all matches, we need to use regular expression with a /g flag.
<button onclick="myFunction()">Try it</button><p id="demo">Please visit Yahoo and yahoo </p><script>
function myFunction() {
var str = document.getElementById("demo").innerHTML;
var txt = str.replace(/YahOO/ig,"Google");
document.getElementById("demo").innerHTML = txt;
}
</script>Output:
Please visit Google and Google
toLowerCase()
To convert a string to lower case we will use toLowerCase() method.
<button onclick="myFunction()">Try it</button><p id="demo">Hello World!</p><script>
function myFunction() {
var text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.toLowerCase();
}
</script>Output:
hello world!
toUpperCase()
To convert a string to upper case we will use toUpperCase() method.
<button onclick="myFunction()">Try it</button><p id="demo">Hello World!</p><script>
function myFunction() {
var text = document.getElementById("demo").innerHTML;
document.getElementById("demo").innerHTML = text.toUpperCase();
}
</script>Output:
HELLO WORLD!
concat()
To join two or more strings we use concat() method. We can also use + operator for concat operation.
<p id="demo"></p>
<script>
var text1 = "Hello";
var text2 = "World";
var text3 = text1.concat(" ",text2);
document.getElementById("demo").innerHTML = text3;
</script>Output:
Hello World
Or even an easier way, concatanation with + operator.
<p id="demo"></p>
<script>
var text1 = "Hello";
var text2 = "World";
var text3 = text1 + " " +text2;
document.getElementById("demo").innerHTML = text3;
</script>Output:
Hello World
trim()
trim() method removes whitespace from both sides of a text. As example:
<button onclick="myTrim()">Try it</button><script>
function myTrim() {
var str = " Hello World! ";
alert(str.trim());
}
</script>Output: On alert box
Hello World!
charAt()
<p id="demo"></p>
<script>
var str = "HELLO WORLD";
document.getElementById("demo").innerHTML = str.charAt(1);
</script>Output:
E
Converting a text/string to an array:
This is very straightforward to convert a text/string to an array. we can simply use the split() method. Just need to pass a separator as a parameter.
split()
<p id="demo"></p>
<script>
let str = "a1b1c1d1e";
let arr = str.split("1");
let text = "";
let i;
for (i = 0; i < arr.length; i++) {
text += arr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>Output:
a
b
c
d
e
If the separator is “” then the array will be an array of single characters.
p id="demo"></p>
<script>
let str = "a1b1c1d1e";
let arr = str.split("");
let text = "";
let i;
for (i = 0; i < arr.length; i++) {
text += arr[i] + "<br>"
}
document.getElementById("demo").innerHTML = text;
</script>Output:
a
1
b
1
c
1
d
1
e
Number
Javascript does not define different types of numbers, such as integers, short, long, floating-point, etc.
JavaScript Numbers are always 64-bit floating-point numbers. The numbers are stored in 64 bits, where the fraction is stored in bits 0 to 51, the exponent in bits 52 to 62, and the sign in bit 63.
Precision
NaN
NaN means not a number. NaN is a javascript reserved keyword. It indicates that a number is not a legal number.
Trying to do an arithmetic operation with a non-numeric string will produce NaN.
<p id="demo"></p>
<script>
document.getElementById("demo").innerHTML = 100 / "USA";
</script>Output:
NaN
isNaN()
method returns true if the variable is NaN.
<p id="demo"></p>
<script>
let x = 100 / "Apple";
document.getElementById("demo").innerHTML = isNaN(x);
</script>Ouput:
true
NaN is a number.
<p id="demo"></p>
<script>
var x = NaN;
document.getElementById("demo").innerHTML = typeof x;
</script>Output:
number
Number Methods:
toFixed()
method returns a string, with a specified number of decimals.
<p id="demo"></p>
<script>
var x = 9.656;
document.getElementById("demo").innerHTML =
x.toFixed(0) + "<br>" +
x.toFixed(2) + "<br>" +
x.toFixed(4) + "<br>" +
x.toFixed(6);
</script>Output:
10
9.66
9.6560
9.656000
N.B: for working with money toFixed(2) is perfect.
toPrecision()
method returns a string, with a specified length.
<p id="demo"></p>
<script>
var x = 9.656;
document.getElementById("demo").innerHTML =
x.toPrecision() + "<br>" +
x.toPrecision(2) + "<br>" +
x.toPrecision(4) + "<br>" +
x.toPrecision(6);
</script>Output:
9.656
9.7
9.656
9.65600
Converting variables to Numbers:
There are 3 global javascript methods that can be used to convert variables to numbers. These are not number methods, these are global.
Number(), parseInt(), parseFloat()
Number()
: Returns a number, converted from its argument.
Number(true); // returns 1
Number(false); // returns 0
Number("10"); // returns 10
Number(" 10"); // returns 10
Number("10 "); // returns 10
Number(" 10 "); // returns 10
Number("10.33"); // returns 10.33
Number("10,33"); // returns NaN
Number("10 33"); // returns NaN
Number("John"); // returns NaN
The number()
method can be used to convert a Date to a number.
<p id="demo"></p>
<script>
var x = new Date();
document.getElementById("demo").innerHTML = Number(x);
</script>Output:
1621087787974
parseInt()
: Parses its argument and returns an integer.
parseInt("10"); // returns 10
parseInt("10.33"); // returns 10
parseInt("10 20 30"); // returns 10
parseInt("10 years"); // returns 10
parseInt("years 10"); // returns NaN
parseFloat()
: Parses its argument and returns a floating-point number.
parseFloat("10"); // returns 10
parseFloat("10.33"); // returns 10.33
parseFloat("10 20 30"); // returns 10
parseFloat("10 years"); // returns 10
parseFloat("years 10"); // returns NaN
Array
We use variables to store values. If we want to store multiple values then we need multiple variables. Do we still use thousand of variables to store thousands of customer’s names? Ohh no. We use arrays to store multiple values in a single variable. We can loop through the array or simply get a value by passing the array index.
With arrayName:
<p id="demo"></p>
<script>
let names= ["Rahim", "Alex", "Sofia"];
document.getElementById("demo").innerHTML = names;
</script>Output:
Rahim,Alex,Sofia
With arrayName[index]:
<p id="demo"></p>
<script>
let names= ["Rahim", "Alex", "Sofia"];
document.getElementById("demo").innerHTML = names[1];
</scriptOutput:
Alex
Array length property:
The length
property of an array returns the length of an array (the number of array elements).
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.length; // the length of fruits is 4
Array Methods:
toString(), join(), pop(), push(), shift(), unshift(), splice(), concat(), slice()
toString()
method converts an array to a string of (comma separated) array values.
<p id="demo"></p>
<script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.toString();
</script>Output:
Banana,Orange,Apple,Mango
join()
method also joins all array elements into a string, It behaves like toString()
, but we can specify the separator.
<p id="demo"></p>
<script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
document.getElementById("demo").innerHTML = fruits.join(" * ");
</script>Output:
Banana * Orange * Apple * Mango
Add Items to an array:
Adding array items: push() and unshift() methods to add items to an array.
push()
method adds a new element to an array at the end.unshift()
method adds a new element to an array at the beginning.
Both push()
and unshift()
method return the new array length.
push():
<p id="demo1"></p>
<p id="demo2"></p><script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.push("Kiwi");
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = x;
</script>Output:
Banana,Orange,Apple,Mango,Kiwi5
unshift():
<p id="demo1"></p>
<p id="demo2"></p><script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.unshift("Kiwi");
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = x;
</scriptOutput:
Kiwi,Banana,Orange,Apple,Mango5
Remove items from an array and getting the removed items:
pop() and shift() methods remove the items from an array and return the removed item.
The pop()
method removes the last element from an array.
The shift()
method removes the first element from an array.
pop():
<p id="demo1"></p>
<p id="demo2"></p><script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.pop();
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = x;
</script>Output:
Banana,Orange,AppleMango
shift():
<p id="demo1"></p>
<p id="demo2"></p><script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let x = fruits.shift();
document.getElementById("demo1").innerHTML = fruits;
document.getElementById("demo2").innerHTML = x;
</script>Output:
Orange,Apple,MangoBanana
Add or Remove items with the same method:
The splice()
method can be used to add new items in any position to an array or remove items from any position of an array.
splice(p1,p2,p3):
The first parameter (p1) defines the position where new elements should be added (spliced in).
The second parameter (p2) defines how many elements should be removed.
The rest of the parameters (p3,…) define the new elements to be added.
The splice()
method returns an array with the deleted items.
adding items in any position with splice():
<p id="demo1"></p>
<script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let removed = fruits.splice(2, 0, "Lemon", "Kiwi");
document.getElementById("demo1").innerHTML = fruits;
</script>Output:
Banana,Orange,Lemon,Kiwi,Apple,Mango
remove items from any position with splice():
<p id="demo"></p>
<script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
fruits.splice(0, 2);
document.getElementById("demo").innerHTML = fruits;
</script>Output:
Apple,Mango//if fruits.splice(2,1); output: Banana,Orange,Mango
add, remove, get items with splice():
<p id="demo1"></p>
<p id="demo2"></p>
<script>
let fruits = ["Banana", "Orange", "Apple", "Mango"];
let removed = fruits.splice(2, 2, "Lemon", "Kiwi");
document.getElementById("demo1").innerHTML = "New Array: " + fruits;
document.getElementById("demo2").innerHTML = "Removed Items: " + removed;
</script>Output:
New Array: Banana,Orange,Lemon,KiwiRemoved Items: Apple,Mango
slice() method:
slice()
method slices out a piece of an array into a new array. It will not change the old array.
The slice()
method can take two arguments like slice(1, 3)
.
The method then selects elements from the start argument, and up to (but not including) the end argument.
<p id="demo"></p>
<script>
let fruits = ["Banana", "Orange", "Lemon", "Apple", "Mango"];
let newArray = fruits.slice(1);
document.getElementById("demo").innerHTML = "Old: "+fruits+"<br/>"+"New: "+newArray;
</script>Output:
Old: Banana,Orange,Lemon,Apple,Mango
New: Orange,Lemon,Apple,Mango// fruits.slice(3); Output:Apple,Mango
// fruits.slice(0,3); Output:Banana,Orange,Lemon
// fruits.slice(1,3); Output:Orange,Lemon
Merging arrays:
The concat()
method creates a new array by merging (concatenating) existing arrays.
Merging two arrays:
<p id="demo"></p>
<script>
let arr1 = ["Cecilie", "Lone"];
let arr2 = ["Emil", "Tobias", "Linus"];
let myChildren = arr1.concat(arr2);
document.getElementById("demo").innerHTML = myChildren;
</script>Output:
Cecilie,Lone,Emil,Tobias,Linus
Merging multiple arrays:
<p id="demo"></p>
<script>
let arr1 = ["Cecilie", "Lone"];
let arr2 = ["Emil", "Tobias", "Linus"];
let arr3 = ["Robin", "Morgan"];
let myChildren = arr1.concat(arr2,arr3);
document.getElementById("demo").innerHTML = myChildren;
</script>Output:
Cecilie,Lone,Emil,Tobias,Linus,Robin,Morgan
Merging using spread … operator:
<p id="demo"></p>
<script>
let arr1 = ["Cecilie", "Lone"];
let arr2 = ["Emil", "Tobias", "Linus"];
let arr3 = ["Robin", "Morgan"];
let myChildren = [...arr1,...arr2,...arr3];
document.getElementById("demo").innerHTML = myChildren;
</script>Output:
Cecilie,Lone,Emil,Tobias,Linus,Robin,Morgan
Array Sort:
sort(), reverse()
Array Iteration:
forEach(), map(), filter(), reduce(), every(), some(), indexOf(), lastIndexOf(), find(), findIndex()